简体   繁体   中英

Correct way to free memory

Makes a while since I've done some C and I have to refresh my understanding of pointers. Here is a function that modifies the content of a pointer. The question is if this code is correct. Is it enough if I only free the pointer or do I have to free the content of by the pointer

void foo(char **str) {
   // str has been allocated enough bytes for the following text
   *str = "allocate some text";
}

int main(int arc, char *argv[]) {
    char *someString;
    foo(&someString);
    free(someString); // is this the correct place to free
}

Thank you.

No, you don't want to call free() , because you never malloc() -ed the data. More specifically, calling free() on a pointer to a string literal results in undefined behaviour .

You shouldn't free at all in this case. free() should always correspond to a call to a malloc() function.

Here you are 'freeing' constant memory that was never allocated in the first place.

There's something that puzzles me in this code.

Why the comment says "str has been allocated enough bytes for the following text "? Even if it has been allocated, you are assigning to the pointer a new value, so it doesn't buy you anything having allocated that memory.

Anyway, according to this code, free() shouldn't be called.

You don't show in your code, but you write that str has been allocated with enough bytes. So that's fine, and can be free ed, but than you assign the pointer to the constant string to str - *str = "allocate some text"; (and as oli said, causes undefined behavior on free) instead perform strcpy() :

strcpy(str, "allocate some text");

First the call of the method foo should be adjusted, since the parameters don't match. It should look something like

foo(&someString);

But personally I would agree to the place where you called the method free(someString) . Because the application is about to end and you no longer need any pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM