Member Avatar for JE821

I'm not sure if I'm freeing the memory correctly.
I have the following struct and I'm trying to free the pointer in it.

typedef struct RECORD
{
    char* name;
    int score;
}RECORD;

In my main function I have an array of this struct, therefore I'm using a loop to free it.

for(index=0;index<50;index++)
    {
        free(report[index].name);
        report[index].score=NULL;
    }

But then, to test if it worked I print the whole array and I get the following,

╪K3                     0
Donald Knuth            0
                        0
Adele Goldberg          0
                        0
Brian Kernighan         0
Linus Torvalds          0
╪K3                     0
Grace Hopper            0
╪K3                     0
Peter Norton            0
Bill Joy                0
(null)                  0
(null)                  0
(null)                  0
(null)                  0
...                     ...
(null)                  0

did I not free it correctly or did the junk values became the names?
Thanks for the help in advance.

Recommended Answers

All 2 Replies

free() does not change the pointer, it still points to the now-freed strings. Try this

for(index=0;index<50;index++)
    {
        free(report[index].name);
        report[index].name = NULL;
        report[index].score=0;
    }

Also note that NULL refers to pointers, not integers. If you want to initialize an integer to 0 then do that instead of using NULL. Some compilers define NULL like this:#define NULL (char *)0

Member Avatar for JE821

Thanks for the response. It worked.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.