2

i try to allocate a char array with malloc but the size is always "8" :

char *d = malloc(2356 << 1);
printf("size of *d: %d\n", sizeof(d));

output: size of *d: 8

char *d = malloc(2356 * sizeof(*d);
printf("size of *d: %d\n", sizeof(d));

output: size of *d: 8

char *d = malloc(2356 * sizeof(char));
printf("size of *d: %d\n", sizeof(d));

size of *d: 8

Please help me, what's is wrong with my code?

Thanks!

shingosan
  • 21
  • 3
  • `d` is not a character array, it is a pointer to a character. When you allocate memory with malloc like this `d` is a pointer to the first item in that allocated array. – Nathan Wride Oct 21 '20 at 08:05
  • 8 is the size of a pointer on your system – Nathan Wride Oct 21 '20 at 08:05
  • I think there's no way you can find the size of memory allocated by malloc by C compilers. Although, there are some extensions that can tell you the size of the allocated array. More information here: https://stackoverflow.com/questions/1281686/determine-size-of-dynamically-allocated-memory-in-c – iwrestledthebeartwice Oct 21 '20 at 08:14
  • You need to keep track of the size yourself. – Jabberwocky Oct 21 '20 at 08:26

1 Answers1

1

You cannot find the size of memory allocated by malloc using sizeof() method. But, instead, there are OS-specific functions that can be used to find the allocated size.

If you are in windows you can use _msize() function in malloc.h header file. It will return the size in bytes.

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

int main(){
    char *d = malloc(2356 << 1);
    printf("size of *d: %d\n", _msize(d));
    //size of *d: 4712

    char *e = malloc(2356 * sizeof(*e));
    printf("size of *d: %d\n", _msize(e));
    //size of *d: 2356

    char *f = malloc(2356 * sizeof(char));
    printf("size of *d: %d\n", _msize(f));
    //size of *d: 2356
    return 0;
}

You can find more info about other OS-specific functions in this thread: Determine size of dynamically allocated memory in C