rahman
rahman

Reputation: 4948

Problem using free() function

I have a C program that uses char *str[xx] staff frequently. Some of the strings are filled using assignment operator(=) and need not be freed. But some other(in the same array) are filled using strdup() which needs to be freed at the end of the program:

char *str[10];

str[i]="Hi";

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

both of the string pointers are non null, and freeing str[i] will naturally generate "seg fault". My problem is that at the end of my program, I don't have a track of which pointer is pointing to a string generated by strdup() . can you help my how I can find the string generated by strdup so that i can free them up? thank you

Upvotes: 4

Views: 473

Answers (3)

mouviciel
mouviciel

Reputation: 67889

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

You have to refactor your program to reach this goal.

Upvotes: 0

Scott C Wilson
Scott C Wilson

Reputation: 20046

Perhaps you could use a naming convention to help you remember which is which:

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 which indicates that this particular pointer was dynamically allocated)

Upvotes: 0

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133122

Unfortunately there is no language feature by which you can (portably) distinguish a pointer which points to a dynamically allocated memory from the one that doesn't. You can just manually keep a list of indices for which it was allocated dynamically. Or alternatively, choose to ALWAYS allocate on the heap, if performance is not a great issue.

Upvotes: 6

Related Questions