1

I am trying to allocate space for 100 integers. But end up with 2 and have not a clue why! I tried both malloc() and calloc but understandingly there is no difference.

Code:

#define MAX 100

    int *arr = (int *)calloc(MAX, sizeof(int)); //same with malloc(MAX * sizeof(int))

    printf("MAIN before memset: %d | %d\n",
    (int)(sizeof(arr)/sizeof(arr[0])), (int)(sizeof(arr)));

    if(!arr) {
            fprintf(stderr, "A malloc error occured.\n");
            exit(1);
    }
    memset (arr, 0, MAX);
    printf("MAIN: %d\n", (int)(sizeof(arr)/sizeof(arr[0])));

OUTPUT:

MAIN before memset: 2 | 8
MAIN: 2

What am I coming short of? I simply want to allocate an array/pointer to 100 integers.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Dimitar
  • 4,402
  • 4
  • 31
  • 47

1 Answers1

2

In your code, arr is a pointer, and using sizeof on a pointer gives you the size of the pointer, not the amount of memory allocated to that pointer.

In your case, sizeof(arr) gives you the size of a int * and sizeof(arr[0]) gives you the size of an int, based on your platform and compiler.

That said, you cannot directly get the size of allocated memory from the pointer itself, you need to keep track of it yourself.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261