Search code examples
cmallocsizedynamic-arraysrealloc

How to properly use malloc() and realloc() when pointing to a struct?


This is my code:

#include <stdio.h>
#include <stdlib.h>

typedef struct{
    char name;
    char surname;
    int month;
    int day;
} person;

person *ptr;
int action, number_of_friends=0, a, b, day, month;
char decision;

int main(void)
{
    ptr=(person*)malloc(sizeof(person));
    while(1)
    {
        printf("Please enter the data about the person number %d\n", number_of_friends+1);
        person entered_person;
        printf("Initial of the name: "); scanf(" %c", &entered_person.name);
        printf("Initial of the surname: "); scanf(" %c", &entered_person.surname);
        printf("The day of birth: "); scanf("%d", &entered_person.day);
        printf("And the month: "); scanf("%d", &entered_person.month);
        *(ptr+number_of_friends) = entered_person;
        printf("Do you want to add more friends? (y/n) ");
        scanf(" %c", &decision);
        if (decision=='n' || decision=='N') {
            break;
        }
        number_of_friends++;
        ptr=realloc(ptr, number_of_friends);
    }
    number_of_friends++;
    person get_person;
    for (a=0; a<number_of_friends; a++)
    {
        get_person = *(ptr+a);
        printf("Person number %d\n", a+1);
        printf("Initial of the name: %c\n", get_person.name);
        printf("Initial of the surname: %c\n", get_person.surname);
        printf("The day of birth: %d\n", get_person.day);
        printf("And the month: %d\n\n", get_person.month);
    }
}

The problem is that it won't display the list of entered people correctly if the number of people is greater than... something like 5.

I believe this is connected with malloc() and realloc() (writing out-of-bounds?) but as a beginner I don't know how to solve that problem.


Solution

  • Your realloc() size is wrong, you want number_of_friends multiplied by the size of a person struct (I'm guessing):

    ptr=realloc(ptr, number_of_friends*sizeof(person));
    

    Edit: Also this is going to crash after the first loop:

    number_of_friends++;
    ptr=realloc(ptr, number_of_friends);
    

    Since number_of_friends starts at 0