简体   繁体   中英

array size stays the same even after memory allocation

i know this may be silly but i do not understand why after i use malloc to allocate memory for cars, cars size is 8. it does not matter what size i enter to carsAmount, please help. when i checked the array size before allocating it- it was 8. i tried to free it but got an error. i tried using realloc-didnt work.

this is my code snippet:

int* cars = NULL;
int carsAmount;

printf("Enter cars amount:\n");
scanf("%d",&carsAmount);
cars = realloc(cars, (carsAmount)*sizeof(int));

From realloc man page

void *realloc(void *ptr, size_t size);

If ptr is NULL, then the call is equivalent to malloc(size)

Which is equivalent to

cars = malloc(carsAmount*sizeof(int))

The malloc() and calloc() functions return a pointer to the allocated memory that is suitably aligned for any kind of variable. On error, these functions return NULL.

To check if allocation succeeded, simply check if

if (cars != NULL)
{
    // allocation ok 
} else {
   // Allocation failed
}

sizeof(int*) / sizeof(int)
    |            |
    V            V
sizeof(cars)/sizeof(int)

Is actually size of pointer which is probably 8 and size of int is probably 4. This is why you get 2.

It's not clear from the question how you are trying to get the array size, but I am guessing you are using sizeof(cars) and always getting 8. That's because sizeof(cars) will give you the size of the cars pointer, and all pointers in a 64-bit architecture are 8 bytes long.

Malloc and realloc keep the size of the buffer internally but you as the user are supposed to keep track of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM