Question:
memory leak at strdup! what do I free?
2010-02-19 00:42:13 UTC
i'm new to c.
this is my for loop... I have a memory leak at _strdup()! what do I have to free in order to get rid of it?

for (linenr = 1; ; ++linenr) {
char *nlpos = NULL;

// Read a line of input and check to see if it ends with
// a newline character. Print a message if not.

char *gotline = fgets (buffer, sizeof buffer, stdin);
if (gotline == NULL) break;

nlpos = strchr (buffer, '\n');
if (nlpos != NULL) {
*nlpos = '\0';
head=insertascending(head, strdup(buffer));
}else {
xfprintf (stderr, "%s: %d: unterminated line: %s\n",
progname, linenr, buffer);
};
};
Four answers:
Brian
2010-02-19 07:00:43 UTC
dtk is correct that strdup() returns memory that must be freed. It's hard to tell you what to free since you haven't told us what "head" is, or what "insertascending()' does. Since you say this is C, not C++, I am going to assume that "head" is a struct and insertascending() returns a pointer to struct with a copy of buffer assigned to one of it's members. If this is so, then when you free the struct (or if it's statically allocated, before it goes out of scope), you must specifically free the member of the struct that you assigned the strdup to.



Something like this:



struct head_struct {

int value;

char *line;

int other_thing;

};



struct head_struct *head;



head = malloc(sizeof(struct_head);

head->line = strdup(buffer);



...do something with head struct



/* all done with head */

free(head->line);

free(head);
dtk
2010-02-19 01:42:04 UTC
The strdup() function returns a pointer to a copy of the string. The memory for the copy is allocated by malloc() and should be freed with free() when you don't need it any more. For example:



char *cpy;

cpy = strdup(mystring);

doStuff(cpy);

free(cpy);
2016-09-30 06:19:42 UTC
Strdup
2010-02-19 00:51:01 UTC
Hard to say, you aren't calling malloc anywhere in the code you posted, so your leak must be elsewhere.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...