Home > Software design >  Memory allocation and freeing not working
Memory allocation and freeing not working

Time:04-20

I'm trying to create dynamically allocated array of structures in C (VS 2022) but the program keeeps crashing while freeing the memory with problem:

Unhandled exception at 0x00007FF9261ECF5D (ntdll.dll) in t3.exe: A LIST_ENTRY has been corrupted (i.e. double remove).

Code:

void task() {
    int i, j, size = 32;
    struct Student tmp;
    struct Student * students = (struct Student*)malloc(size*sizeof(students));
    for (i = 0; i < size; i  ) {
        scanf(" %s", &students[i].name);
        scanf(" %s", &students[i].lastname);
        scanf(" %d", &students[i].index);
        scanf(" %s", &students[i].major);
        scanf(" %d", &students[i].semester);
        scanf(" %d", &students[i].grp);
    }
    free(students);
}

Should I also allocate every struct element manually in for loop right after getting input and then free it the same way?

CodePudding user response:

You should malloc(sizeof(struct Student) instead of students which is just a size of pointer.

CodePudding user response:

sizeof( students ) in this declaration

struct Student * students = (struct Student*)malloc(size*sizeof(students));

is equivalent to sizeof( struct Student * ). But you need to use sizeof( struct Student ) or sizeof( *students ) because you need to allocate an array of objects of the type struct Student.

Also these calls of scanf

scanf(" %s", &students[i].name);
scanf(" %s", &students[i].lastname);
scanf(" %s", &students[i].major);

you need to rewrite at least like

scanf(" %s", students[i].name);
scanf(" %s", students[i].lastname);
scanf(" %s", students[i].major);

If the data member major has the type char then you need to write

scanf(" %c", &students[i].major);

Also name and lastname (and major if it does not have the type char) must ne chracater arrays.

CodePudding user response:

replace

struct Student * students = (struct Student*)malloc(size*sizeof(students));

with

struct Student * students = (struct Student*)malloc(size*sizeof(struct Student));

Also since you are using a pointer you would need to reference the variables with ->

  • Related