DEV Community

Naman Tamrakar
Naman Tamrakar

Posted on • Edited on

A common pitfall when using sizeof() with pointers

There is a common mistake made by new student when they use sizeof operator with pointers to get number of bytes allocated.

NOTE: sizeof returns the size in bytes and 1 byte = 8 bit

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

int main() {
    char *c = malloc(10);

    printf("Bytes allocated: %ld\n", sizeof(c));
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

They expect the output of above program as 10 bytes. But it doesn't work like that.

The output will be

Bytes allocated: 8
Enter fullscreen mode Exit fullscreen mode

But why? When we allocated 10 bytes then it should output 10 bytes. Why It is showing 8 bytes?

Then answer to this question is in the above code we are not measuring the amount of bytes allocated but the size of pointer which will be 8 bytes for all 64 bit compiler and 4 bytes for 32 bit compiler. (My compiler is 64-bit)

So If one want it to get later it should be store in some variable explicitly.

Now the question how we are able to do same for an array which also behaves like pointer.

Let's check the below example.

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

int main() {
    int c[10];

    printf("Bytes allocated: %ld\n", sizeof(c));
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output

Bytes allocated: 40
Enter fullscreen mode Exit fullscreen mode

The output of above program is as expected because the size of int is 4 bytes so total 4x10 = 40 bytes it returns.

In the above statement it said array behaves like pointer but it isn't. It is allocated in stack not heap that may be one of the reason that sizeof is able to get size of bytes allocated to an array.


❤️Thank you so much for reading it completely. If you find any mistake please let me know in comments.

Also consider sharing and giving a thumbs up If this post help you in any way.

Top comments (2)

Collapse
 
pauljlucas profile image
Paul J. Lucas
Bytes allocated: 1
Enter fullscreen mode Exit fullscreen mode

No, 8. You even say so in the text.

Collapse
 
namantam1 profile image
Naman Tamrakar

Thanks. I updated the output