1

I've got a very simple piece of C code that uses malloc and realloc, but it induces a seg fault if I change a value that was part of the first array.

#include <stdlib.h>

void increase(int** array) 
{
    int * new_array;
    new_array = realloc(*array, 10 * sizeof(int));
    if (new_array != NULL) {
        *array = new_array;
    }
    else {
        // Error in reallocation
    }
    int i = 3;
    *array[i] = 2; // Seg fault if i = 0, 1, 2, 3
}

main()
{
    int *array = malloc(4 * sizeof(int));
    increase(&array);
    free(array);
}

Is my understanding of pointers at fault? Can anyone explain what's happening and how I can use realloc properly?

Many thanks!

1 Answer 1

6

You probably need:

(*array)[i] = 2;

The [] operator binds before the *, so your version was doing *(array[i]) which is, well, wrong.

Sign up to request clarification or add additional context in comments.

4 Comments

Yup, that'll do it, thanks. Can you explain why this is needed?
Operator precedence - the array indexing is happening before the pointer dereference, but you want the other way around.
To give a bit more detail. The previous version without () is interpreted as *(array[i]).
You saved my day... after I've already lost yesterday night. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.