What happened to realloc?

He began to study malloc.h in C. The idea was to create a dynamic array. Here is the code:

#include <stdio.h>
#include <conio.h>
#include <malloc.h>

int main() {
    int *array = (int*)malloc(sizeof(int));
    int i, j, val;
    for (i = 0;; i++) {
        array = (int*)realloc(array, sizeof(int) + sizeof(*array));
        printf("Enter array[%d]=", i);
        scanf("%d", (array + i));
        if (*(array + i) == 0) break;
    }
    for (j = 0; j < i; j++) {
        printf("[%d] = %d\n", j, *(array + j));
    }
    getch();
    return 0;
}

Result

Enter array[0]=1
Enter array[1]=2
Enter array[2]=3
Enter array[3]=4
Enter array[4]=5
Enter array[5]=6
Enter array[6]=7
Enter array[7]=8
Enter array[8]=9
Enter array[9]=10
Enter array[10]=0
[0] = 1
[1] = 2
[2] = 3
[3] = 4
[4] = 5
[5] = 6
[6] = 7
[7] = 8
[8] = 542979931
[9] = 875896893

Each time the values >=8are random. I just don't know why this is happening, so what's wrong?

+5
source share
4 answers

Undefined behavior in your code. I suppose by doing this:

array=(int*)realloc(array,sizeof(int)+sizeof(*array));

you expect to sizeof(*array)return the size of the entire array to you, right? But this is not so. sizeofcomputed at compile time, but sizeof(*array)actually matches sizeof(int).

So, to make this array extensible, you need to have an additional variable, holding the current number of elements and doing something like:

array=(int*)realloc(array, sizeof(int) + current_size_of_array * sizeof( int ) );

current_size_of_array for, .

+7

sizeof(*array) , . , int. realloc int. realloc, sizeof(int) int.

+3

sizeof(int)+sizeof(*array)

, sizeof(*array) - . , sizeof(*array) - int. , , .

, . ( ++ - , malloc, vector). , , i.

+2

, malloc, (free ), . - , .

sizeof(*array) sizeof (*(int *)), , , sizeof(int).

++ , , std::vector.

As a note, note that this x = realloc(x, ...);is a bad idiom, because in the event of a selection failure, your pointer xwill be overwritten NULLby a memory leak.

+1
source

All Articles