I ran into a terrible error in testing some code. I figured out that it was caused by calling free(p_current_item->s) where p_current_item is a node in a linked list, and s is the char* it contains. I created the node by calling a method addItem(node,char*) which simply adds the element to the list: p_head=addItem(p_head,"this gets added");
What is bothering me is:
1) Why I would need to free the string contained in the element. I know it is necessary when s is declared as char* s = snprintf(s,(size_t),30,"this gets added"); (which is how it was done in my class example) but why is that necessary- is it possible to have the attributes contained within a struct (in this case the linkedList node) be freed when the struct itself is freed?
2) what was happening when I tried to free the value of s which was explicitly declared
3) Do i need to free up the value of s some other way?
Thanks 🙂
You can only
freememory which has been allocated using themallocfamily of calls.Strings encapsulated in double quotes are compile time constants. They get imported into your runtime program together with the instruction text. Thus those have not been allocated dynamically.
Also
snprintfreturns the length of the produced string, not a pointer to it. the correct usage would be:1) You only need to free
sif it was allocated usingmalloc,callocor another call from that family. e.g.char* s = malloc(1024);2)
free("constant string");will at best result in a segmentation violation because you are trying to deallocate memory which has not been allocated by themallocfamily of calls. Generally this is undefined behaviour.3) You do not need to free constant strings, they are part of your text and cannot be freed even if you wanted to do so.