0

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.

Edited by JE821

2
Contributors
2
Replies
13
Views
4 Years
Discussion Span
Last Post by JE821
1

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

0

Thanks for the response. It worked.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.