Search code examples
cstructmallocsizeofrealloc

invalid size of struct after realloc


I want to load records from a file into a dynamic array. I have the following code:

typedef struct my_data {
    char name[100];
}my_data;
struct my_data *data;

void load_data()
{
struct my_data *temp = NULL;
    int i = 0;
    FILE * in;
    if((in = fopen("data.txt","rt")) != NULL) {
    temp = malloc((i+1)*sizeof(my_data));
    while(!feof(in))
        {
            fscanf(in,"%s", &temp[i].name);
            i++;
            temp = realloc(temp,((i+1)*sizeof(my_data)));
        };
        fclose(in);
    data = temp;
    free(temp);

    for (i=0;i<sizeof(data);i++ )
        printf("%s\n",data[i].name);
    }

I have over 100 records. Why does it show only 4?


Solution

  • sizeof(data)
    

    Above gives the size of data which is of type my_data *, 4 bytes on your system. To get the number of records, follow the same logic as how you allocated the memory (i.e., i+1 records). Note that you have reassigned i to 0 in the for loop initialization expression.