简体   繁体   中英

C realloc segmentation fault

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!

You probably need:

(*array)[i] = 2;

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

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