0

I want to print out the capacity of my dynamic arrays, but no matter how I change it, it keeps saying that the capacity of both the arrays are 2.

The code (tmp.c)

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

int main(){

  int *ptr1 = (int *)malloc(sizeof(int) * 3);
  int capacity_ptr1 = sizeof(ptr1)/sizeof(int);
  printf("capacity of ptr1 is: %d\n", capacity_ptr1 );

  int *ptr2 = (int *)realloc(ptr1, sizeof(int) * 5);
  printf("capacity of ptr2 is: %ld\n", sizeof(ptr2)/sizeof(int) );



  return 0;
}

What I execute in terminal

gcc -std=c99 tmp.c -o tmp
./tmp

The output in terminal

capacity of ptr1 is: 2
capacity of ptr2 is: 2

I get this output no matter what capacity parameter I enter for malloc() and realloc()

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Coder Motor
  • 123
  • 1
  • 4
  • 1
    `sizeof(ptr2)` doesn't give you the capacity of the allocated memory. All it gives you is the size of an `int` pointer, which stays the same. – Blaze Jul 09 '19 at 06:11
  • 1
    `sizeof` a pointer is the size of the actual pointer, not what it might be pointing to. When you do dynamic allocation in C you have to keep track of the "size" yourself. – Some programmer dude Jul 09 '19 at 06:12
  • [Please see this discussion on why not to cast the return value of malloc() and family in C..](https://stackoverflow.com/q/605845/2173917) – Sourav Ghosh Jul 09 '19 at 06:14
  • `sizeof array / sizeof *array` only apply to *Arrays*, and only within the *scope* in which they were declared. `int *ptr1` declares a pointer, so `sizeof ptr1` is `sizeof (a_pointer)` (generally 8-bytes on x86_64) and `sizeof (int)` is `4`. No matter how many `int` you allocate for `sizeof ptr1 / sizeof (int)` will ways be `2` on x86_64 . – David C. Rankin Jul 09 '19 at 07:01
  • Use search engine. It is one if the most frequent duplicates – 0___________ Jul 09 '19 at 07:05

2 Answers2

1

You take the size of a pointer (not an array), which is usually 64 bits then divide it by the size of an int, which is usually 32 bits. This is why you get 2 as a result.

0

Two things:

  1. Arrays are not pointers, and vice-versa
  2. You are not checking the size of allocated memory, anyways.

To elaborate, the problem here is, sizeof(ptr1) does not yield the size of the valid memory pointed to by the pointer, it returns the size of the pointer itself. Size of a pointer (or any type, for that matter), is constant.

For the pointers returned by allocator functions, there's so straight way to get the size of the requested (and allocated) memory size from the pointer itself, you need to keep track of the size yourself.

That said: Please see this discussion on why not to cast the return value of malloc() and family in C..

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