2

I'm experiencing some behavior I don't understand with malloc.

For instance, allocating memory for a structure works just fine, i.e.:

typedef struct my_struct {
        char buffer[4096];
        struct my_struct *next;
} MY_STRUCT;

...

MY_STRUCT *ptr = (MY_STRUCT *)malloc(sizeof(struct my_struct));
        printf("malloc() gave us %lu bytes\n", sizeof(*ptr));
        printf("My structure's first member is %lu in length\n", sizeof(ptr->buffer));
        free(ptr);

...

Returns

malloc() gave us 4104 bytes
My structure's first member is 4096 in length

...exactly as expected. Now, when I try to dynamically allocate a buffer for a character string:

int bufsize = 4096;
char *buffer = (char *)malloc(sizeof(char)*bufsize);
printf("bufsize: %d\n", bufsize);
printf("Allocated buffer size: %lu\n", sizeof(*buffer));
free(buffer);

...returns

bufsize: 4096
Allocated buffer size: 8

Now, I can hard-code the malloc() call to 4096, 1, 4, anything really... It always comes up 8.

What am I getting wrong here?

Daniel Cassidy
  • 24,676
  • 5
  • 41
  • 54
  • 1
    You can't use the pointer returned by `malloc` to find the memory allocated. The memory allocated, if successful, is what was asked for, that is, you already know it. – Weather Vane Nov 20 '15 at 19:31
  • 1
    [Obligatory warning about casting the result of malloc in C](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – Paul R Nov 20 '15 at 19:31
  • 1
    Hmm -- there's something else weird in op's post. `sizeof(*buffer)` for `char* buffer` should give 1, not 8. –  Nov 20 '15 at 19:39
  • 2
    The correct format for printing a `size_t` value (such as the result of `sizeof`) is `"%zu"`. `sizeof(*buffer)` *should* yield `1`, not `8`. The declaration of `buffer` is more simply written as `char *buffer = malloc(bufsize);`. `malloc()` returns `NULL` if it fails; always check for that. If it doesn't return `NULL`, it allocated the size you asked it to. – Keith Thompson Nov 20 '15 at 19:39
  • ^^ It's odd how often the most complete answer (Keith's) is in the comments. –  Nov 20 '15 at 19:42

1 Answers1

5

sizeof tells you what the compiler thinks the size of something is.

If ptr is a MY_STRUCT*, then sizeof(*ptr) will always be the same as sizeof(MY_STRUCT). That's true even if ptr points to NULL, or to an array of MY_STRUCTs, or to memory that's already been freed, or so on.

sizeof cannot be used to tell you the size of a memory block allocated with malloc.

user253751
  • 57,427
  • 7
  • 48
  • 90