Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sizeof with a dynamically allocated array

Tags:

c

sizeof

gcc 4.4.1 c89

I have the following code snippet:

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

 char *buffer = malloc(10240);
 /* Check for memory error */
 if(!buffer)
 {
    fprintf(stderr, "Memory error\n");
    return 1;
 }
 printf("sizeof(buffer) [ %d ]\n", sizeof(buffer));

However, the sizeof(buffer) always prints 4. I know that a char* is only 4 bytes. However, I have allocated the memory for 10kb. So shouldn't the size be 10240? I am wondering am I thinking right here?

Many thanks for any suggestions,

like image 754
ant2009 Avatar asked Apr 28 '10 16:04

ant2009


1 Answers

You are asking for the size of a char* which is 4 indeed, not the size of the buffer. The sizeof operator can not return the size of a dynamically allocated buffer, only the size of static types and structs known at compile time.

like image 175
Péter Török Avatar answered Nov 08 '22 06:11

Péter Török