-1

I have this struct Exam. and i am using cleanUp function to allocate and free the memory occupied by title but its not freeing it.

    typedef struct
    {
        char* title;
        Question* questions[MAX_QUESTIONS];
    }Exam;

    BOOL CleanUp(Exam * e){
    char name[200];
        printf("Enter name of the course \n");
        gets(name);
        fflush(stdout);
        e->title = (char*)malloc(sizeof(strlen(name)+1));
        strcpy(e->title,name);

        free(e->title);
    }
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97

3 Answers3

2

sizeof(strlen(name)+1) is not correct, this gives you the size of the result of that calculation, i.e. sizeof(int). Because you have allocated the wrong size you are writing past the end of the buffer.

This is corrupting data and causing free() to fail.

What you mean to do is:

sizeof(char) * (strlen(name) + 1)

In C, sizeof(char) is guaranteed to be 1, so you don't actually need it here, however I've put it there to illustrate the general way to allocate memory for multiple objects: multiply the size of the object by the number of objects.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
Zebra North
  • 11,412
  • 7
  • 37
  • 49
0

Surely you simply meant:

e->title = strdup(name);

...

free(e->title);

strdup() will count the string pointed to by 'name', allocate space for a copy (including the null terminator) and copy the data in a sensible, architecture aligned way (usually.)`

Whilom Chime
  • 366
  • 1
  • 9
0

I think Whilom Chime gave a pretty adequete answer, as did Mr. Zebra. Another way to do it would be like so;

e->title = malloc(sizeof(char *));

if(e->title != NULL) strcpy(e->title, word);

However, I've found when working with really large data sets (I had to put ~3M words into a 2-3-4 tree a couple days ago), e->title = strdup(word); is actually faster than strcpy(e->title, word);. I don't know why, and it honestly doesn't make sense to me, seeing as strcpy doesn't have to go through the process of allocating memory for the character pointer. Maybe someone else can give input on this

h3xc0ntr0l
  • 399
  • 1
  • 3
  • 14