The correct way to free memory

It does some time since I made some C, and I need to update my understanding of pointers. Here is a function that modifies the contents of a pointer. The question is whether this code is correct. Is it enough if I free only the pointer or do I need to free the contents with a 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.

+3
source share
5 answers

No, you do not want to call free()because you have never malloc()used data. More specifically, a call free()in a pointer to a string literal results in undefined behavior.

+10
source

. free() malloc().

"" , .

+2

- .

: "str " , , , .

, , free() .

+1

, , str . free ed, string - *str = "allocate some text"; (, oli, undefined ), strcpy():

strcpy(str, "allocate some text");
+1

First, the call to the foo method must be adjusted, since the parameters do not match. It should look something like this:

foo(&someString);

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

-2
source

All Articles