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.
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.
free()
malloc()
. free() malloc().
"" , .
- .
: "str " , , , .
, , free() .
, , str . free ed, string - *str = "allocate some text"; (, oli, undefined ), strcpy():
free
*str = "allocate some text";
strcpy()
strcpy(str, "allocate some text");
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.
free(someString)