Problem using the free () function

I have a C program that often uses char *str[xx] staff. Some lines are filled with the assignment operator (=) and do not need to be freed. But some others (in the same array) are populated with strdup() , which should be freed at the end of the program:

char * str [10];

str [I] = "Hello";

str [k] = strdup ("hello");

both line pointers are not null , and releasing str [i] will naturally generate a "seg fault". My problem is that at the end of my program, I do not have a track whose pointer points to the line generated by strdup() . can you help me, how can I find the string generated by strdup so that I can free them? thanks

+4
source share
3 answers

The proper way to handle this is to keep track of what has been dynamically allocated through malloc() or strdup() .

You need to reorganize your program to achieve this.

0
source

Unfortunately, there is no language function due to which you can (portable) distinguish between a pointer that points to dynamically allocated memory from one that does not. You can simply manually save the list of indexes for which it was allocated dynamically. Or, alternatively, select "ALWAYS" to heap if performance is not a big problem.

+6
source

Perhaps you could use a naming convention to help you remember exactly what:

 char *str[10]; char *str_p[10]; str[i]="Hi"; str_p[k]=strdup("hi"); 

(or use a structure with a pointer and a flag that indicates that this particular pointer has been dynamically allocated)

0
source

All Articles