I’m currently playing with linked lists, and I’ve put together the following code for testing purposes.
First I’d like to point out, I’m aware of my unusual list setup, it was just a test, to get a not upside down list. My actual “problem” now is, that I don’t seem to have any memory leaks once the program terminates, although I’m not freeing the list. I’m using drmemory on Windows for analyzing, and it always worked nicely. If I put some other mallocs in this code, it notices the not freed memory. Why doesn’t it notice the list?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// ----------------------
typedef struct Item
{
char name[10];
struct Item *next;
} Item;
Item *items = NULL;
Item *items_add(const char* name)
{
Item *new = malloc( sizeof(Item) );
strcpy(new->name, name);
new->next = NULL;
if(items == NULL)
{
items = new;
}
else
{
Item *iter = items;
while(iter->next != NULL)
{
iter = iter->next;
}
iter->next = new;
}
return new;
}
void items_rem(const char* name)
{
if(items == NULL)
return;
Item *iter = items, *prev;
do
{
if(strcmp(iter->name, name) == 0)
{
prev->next = iter->next;
free(iter);
break;
}
prev = iter;
iter = iter->next;
}
while(iter->next);
}
// ----------------------
int main(void)
{
items_add("Item1");
items_add("Item2");
items_add("Item3");
items_add("Item4");
items_rem("Item3");
for(Item *iter = items; iter != NULL; iter = iter->next)
{
printf("%s\n", iter->name);
}
/*
Output:
Item1
Item2
Item4
*/
}
The reason, I can think of is that
Item *items = NULL‘items’ is a global variable. So, as far as the memory leak checking tool is concerned, the memory is still accessible from the code, so it may be assuming that you still need that memory.Atleast IBM Rational Purify works in this way. In IBM Rational Purify, you can select the option to show “Memory in use” and it will display this pointer and number of bytes held by it.
Please note that a memory is considered leaked only when there are no pointer variables containing that address and it has not been freed also.
For Ex:
Now, in the above example, once you return from function, there is no way for you to access variable
ptr. So, the memory allocated for ptr is definitely lost