Giorgos Mouch
Giorgos Mouch

Reputation: 70

realloc an array with c

I tried to find similar title questions with mine, but I didn't find what I wanted. So here is my question. If I malloc an array with size of 10, is it able to realloc the size and make it 9? And the 8 etc etc ? And if it's able, if I have this array: [1,2,3,4,5,6,7,8,9,10] How can I know which cell will be deleted ? Is it able to choose which one to delete every time ?

Upvotes: 1

Views: 2169

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148880

When you realloc with a smaller size, many implementation just do nothing: you have a bloc that can hold at least 10 elements, it can hold at least 8 elements. Simply you shall no longer use the elements past the declared size. Nothing will prevent you to do it, but it just invokes Undefined Behaviour.

It can be surprising for beginners:

int *arr = malloc(10 * sizeof(int));   // allocate an array of 10 int
for (int i=0; i<10; i++) {             // initialize it with 0-9
    arr[i] = i;
}
arr = realloc(arr, 8*sizeof(int));     // realloc the array to 8 elements
for (int i=0, i<8; i++) {
    printf(" %d", i);
}
printf("\n");                          // should have correctly printed 0 1 ... 7
// the interesting part
for (int i=8; i<10; i++) {
    printf(" %d", i);                  // Oops, UB!
}
printf("\n");                          // but what is to be expected is just 8 9...

Now it works but is UB. Say differently never pretend that I said that it was correct code. But most implementations will accept it and will give the expected result (which is allowed by UB...) without any other side effect.

Upvotes: 2

ArrayIndexOutOfBounds
ArrayIndexOutOfBounds

Reputation: 366

The realloc() and reallocarray() functions serve this purpose. The method header is actually:

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

Where *ptr is the pointer to the memory that you want to reallocate.

However, you can't choose. If you increase the size, the old elements will remain as they are, and there will be some elements at the end that are undefined (null). If you decrease it, the memory space will be "cut", that means, if you have space for 10 elements, and you realloc for 6, the last 4 elements will not be accessible.

If you want to achieve that behaviour, arrange your array before reallocating

Much more information can be found in the man pages (enter link description here) and in several websites.

Upvotes: 1

Related Questions