开发者

Correct way to free memory

开发者 https://www.devze.com 2023-03-05 04:16 出处:网络
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 enou

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开发者_StackOverflow中文版

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 freeed, 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消