0

I'm looking for if it is possible to enlarge array size in C without losing old values, which is I guess append function in Python.

int size_arr = 1;
int *arr = (int *)malloc(sizeof(int)*size_arr);
// Let's give first element of arr to 1
*(arr+0) = 1;
size_arr++;
//Realloc, but I lost *(arr+0) = 1
arr = (int *)realloc(arr, size_arr);
  • Detail: Code is not changing the size of an array. It is changing the memory allocated. In C, once an _array_ is defined like `int a[42]`, its size cannot change. `int *arr` is a pointer. Changing the memory allocation though is what is done here and is quite common. – chux - Reinstate Monica Apr 09 '18 at 21:20
  • [don't cast malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Barmar Apr 09 '18 at 21:40

2 Answers2

5

You are actually reducing the allocated space, not increasing it. Both malloc and realloc take the size in bytes that you want to allocate / resize. And the size in bytes for an int is size * sizeof(int).

You realloc call should look like this:

int *tmp = realloc(arr, size_arr * sizeof *tmp);
if(tmp == NULL)
{
    fprintf(stderr, "Not enough memory\n");
    // arr is left intact, the memory is still allocated

    // Error handling, for example
    free(arr);
    return 0;
}

arr = tmp;

now you have space for size_arr integers.

Note that is a good practice to use a temp variable for storing the result of realloc. When realloc fails, the original memory is not freed, so if you don't use a temp variable, then you are losing the pointer to the orginal memory.

Also, don't cast malloc and realloc.

Pablo
  • 13,271
  • 4
  • 39
  • 59
3

Just compare the two lines of your code:

int *arr = (int *)malloc(sizeof(int)*size_arr);
arr = (int *)realloc(arr, size_arr);

Do you see the difference in last arguments of both calls? Since when reallocating you shrink your array to two bytes, array contents is lost and behaviour becomes slightly undefined.

Give realloc a proper size and you'll see it preserves your original data.

bipll
  • 11,747
  • 1
  • 18
  • 32