I came across an issue that I am not sure if it’s an issue at all. I have a simple C funcion that gets a char* passed from string like so:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
passString("hello");
return (EXIT_SUCCESS);
}
void passString(char * string) {
// .... some code ....
free(string); // ???
}
and I was taught to free every memory block that I’m not working with anymore (mainly arrays). So my though was to free string as well but the program freezes or crashes even with this simple example. I’m not sure whether I really need to free string here or not and if so how do I achieve that?
You do not need to
freememory which you did not allocate withmalloc.In your example
stringis not allocated bymallocin your program so you do not need to free it.stringis a string literal and is allocated somewhere in the read-only memory(implementation defined) and is automatically freed.For standerdese fans:
References:
c99 Standard: 7.20.3.2 The
freefunction