Roma  Karageorgievich Roma Karageorgievich - 2 months ago 11
C Question

How to properly free an allocated memory in C?

I have two functions. In

find_host(...)
I allocated memory which I want to
free
in
main
function.

char* find_host(char* filename){
char *x = malloc(20);
sprintf(x, filename);
const char* t = "10";
int len = (int) strcspn(filename, t);
x[len] = '\0';
return ++x;
}

int main(){
char *filename = "/CERN0/out_79.MERGE";
char *word = find_host(filename);
free(word);
return 0;
}


But
free(word)
gives me:

*** Error in `/home/ken/.CLion2016.2/system/cmake/generated/First-6a656bbe/6a656bbe/Debug/First': free(): invalid pointer: 0x00000000008b1011 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x77725)[0x7f926862f725]
/lib/x86_64-linux-gnu/libc.so.6(+0x7ff4a)[0x7f9268637f4a]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7f926863babc]
/home/ken/.CLion2016.2/system/cmake/generated/First-6a656bbe/6a656bbe/Debug/First[0x4006e9]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7f92685d8830]
/home/ken/.CLion2016.2/system/cmake/generated/First-6a656bbe/6a656bbe/Debug/First[0x400579]
======= Memory map: ========


How should correctly
free
memory?

jxh jxh
Answer

You can only call free() on the pointer value actually returned by a call to malloc() and its brethren. Since you wish to skip the initial character, you can do the skipping when you populate the buffer rather than return an altered pointer.

char* find_host(char* filename){
    size_t sz = strlen(filename);
    char *x = malloc(sz);
    snprintf(x, sz, "%s", filename + 1);
    const char* t = "10";
    int len = (int) strcspn(filename, t);
    x[len] = '\0';
    return x;
}