user3265447
user3265447

Reputation: 129

calloc sometimes gives double the amount of memory asked

I came across something I don't understand why and I'd like to hear an explanation about it. I have this struct:

typedef struct Student {
    int age;
    char *name;
} Student;

int main()
{
    Student **test1 = calloc(2, sizeof(*test1));
    Student **test2 = calloc(2, sizeof(**test2));
    return 0;
}

I've noticed that test1 gets 2 memory allocations (as it should) while test2 gets 4. Why is that and which is the correct usage? I assume its the first one but i'm not sure why.

Thanks!

Upvotes: 0

Views: 136

Answers (3)

0___________
0___________

Reputation: 67751

sizeof(*test) is a size in bytes of the pointer to Student. It will be on most systems 4 or 8.

sizeof(**test)gives you the size of the Student. The allocation (test2) makes no sense at all.

You can easily test it yourself by printing the sizes:

#include <stdio.h>
#include <malloc.h>

typedef struct Student {
    int age;
    char *name;
    double somedata[100];
} Student;

int main()
{
    Student **test1;
    Student **test2;

    printf("%zu\n", sizeof(*test1));
    printf("%zu\n", sizeof(**test2));
    return 0;
}

https://godbolt.org/z/W6e8YzKKf

Upvotes: 2

MikeCAT
MikeCAT

Reputation: 75062

sizeof(*test1) is the size of a pointer Student*, while sizeof(**test) is the size of a structure Student.The structure has a pointer, so its size should be larger than the size of a pointer.

Student **test1 = calloc(2, sizeof(*test1));

Is the typical usage. This is allocating 2-element array of Student* and assigning the pointer to its first element to test1.

Upvotes: 4

dbush
dbush

Reputation: 224387

Two things here:

  1. You're allocating two different amounts of memory here. In the first case, you allocate space for 2 objects of type Student *, while in the second case you allocate space for 2 objects of type Student. The latter is likely larger than the former, so you'll be able to put more object of type Student * there.
  2. You don't show how you're verifying how much memory you've gotten, but it's undefined behavior to read or write past the bounds of allocated memory. Your program might crash, or it might not.

Upvotes: 3

Related Questions