realloc not copying first index

I'm having some trouble with using the malloc/realloc command with arrays. I've created a small array with some integers in it, and tried to add one value to it by expanding the size with realloc and adding the value, but when I do that the 0 index's value is not preserved and is seen as garbage.

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

int main(){
        int n;
        printf("Enter size of array\n");
        int *A = malloc(n*sizeof(int));
        for(int i = 0; i < n; i++){
                A[i] = i + 1;
        *A = realloc(A, sizeof(A)+ sizeof(int));
        A[n] = 1234;
        for(int i = 0; i < n + 1; i++){

        return 0;

and when i run the program this happens:

Enter size of array

Does anyone know why the 0 index of the array is getting this value and not 1?

2 answers

  • answered 2018-03-13 21:42 Stephan Lechner

    Write A = realloc(A, (n + 1) * sizeof(int)); instead of *A = realloc(A, sizeof(A)+ sizeof(int));

    *A = ... will overwrite the value of the first index with a "address value" if A is not moved to another place in memory (undefined behaviour otherwise).

    Note that sizeof(A) is a constant value (probably 8, and not the amount of memory allocated previously), such that you had a good chance that realloc did not move the memory.

  • answered 2018-03-13 21:52 Gilles

    $ gcc a.c
    a.c: In function ‘main’:
    a.c:12:12: warning: assignment makes integer from pointer without a cast [-Wint-conversion]
             *A = realloc(A, sizeof(A)+ sizeof(int));

    Make sure to configure your compiler to emit warnings on code that looks suspicious. Any remotely decent compiler would raise at least a warning, if not an error, on this line. realloc returns a pointer, which you're trying to assign to an int object.

    You need to assign the resulting pointer to A, not *A. Furthermore, there's another error, which compilers can't warn you about. sizeof(A)+ sizeof(int) is too small, and does not make much sense in context. Note that sizeof(A) is the size of the pointer A. There's no way to use sizeof to find the number of items in the array that A points to, because sizeof relies on compile-time information. To extend the array by one element, you need to add sizeof(int) to the current allocated size, which is n*sizeof(int), i.e. the new size should be (n+1) * sizeof(int).

    In addition, it would be better to use sizeof(*A) than sizeof(int). The two are equivalent, but sizeof(*A) has the advantage that it'll still be correct if you decide to change the array elements, e.g. to make them long.

    A = realloc(A, (n+1) * sizeof(*A));