3

So I'm trying to create a dynamic array in C, using malloc, but for some reason it's not working out. Here's my code:

    int* test = (int*) malloc(20 * sizeof(int));
    printf("Size: %d\n", sizeof(test));

The console outputs 8 when I run this code, although it ideally should output 80, I believe, since the size of an int is 4, and I'm creating 20 of them. So why isn't this working? Thanks for any help. :)

Mr Cherno
  • 315
  • 3
  • 10

3 Answers3

8

The sizeof operator is returning the size of an int*, which is just a pointer. In C, when you allocate memory dynamically using malloc, the call to malloc returns a pointer to the newly allocated block of memory (usually on the heap.) The pointer itself is just a memory address (which usually only takes up 4 or 8 bytes on most modern systems). You'll need to keep track of the actual number of bytes allocated yourself.

The C language will only keep track of buffer sizes for statically allocated buffers (stack arrays) because the size of the array is available at compile time.

int test[100];
printf("Sizeof %d\n", sizeof(test))

This will print a value equal to 100 * sizeof(int) (usually 400 on most modern machines)

Charles Salvia
  • 52,325
  • 13
  • 128
  • 140
  • Thanks for the reply. So how can I get the size of a dynamic array? – Mr Cherno May 29 '13 at 00:04
  • 2
    @Mr Cherno, you can't get it using standard ANSI-C. You have to simply keep track of it yourself using a separate variable. (You know you allocated a buffer equal to the size of `20 * sizeof(int)`). – Charles Salvia May 29 '13 at 00:05
  • @CharlesSalvia, one pedantic point, the size of dynamically allocated memory is kept track of otherwise you would have to specify the size when you call free() http://stackoverflow.com/questions/1518711/c-programming-how-does-free-know-how-much-to-free –  May 29 '13 at 09:58
3

Here sizeof operator is giving you the number of bytes required to store an int*
i.e. it is equivalent to sizeof(int*);
Depending on the compiler it may give you 4 or 8

In C its programmers job to keep track of number of bytes allocated dynamically.

Navnath Godse
  • 2,233
  • 2
  • 23
  • 32
Sandesh Kobal
  • 890
  • 9
  • 11
0

if you try to print value of sizeof (&test), you will get 80 (20 * 4). &test is of type int (*) [20].

I hope it clarifies your doubt.

maverick
  • 19
  • 2