Realloc returns NULL

int main() {
    struct lottery *array;      

    array = (struct lottery *)malloc(3000 * sizeof(struct lottery));       
    int opt, counter;

    menu1();
    scanf("%d", &opt);
    if (opt == 1)
        Load(array, &counter);
    else
        exit("0");
    menu2();
    counter--;
    scanf("%d", &opt);
    while (opt != 7) {
        switch (opt) {
        case 1:
            Save(array);
            break;
        case 2:
            Enterd(array, &counter);
            printf("%d\n", counter);
            break;
        }
        menu2();
        scanf("%d", &opt);
    }
    return 0;
}

void Enterd(struct lottery *a, int *count) {
     struct lottery *b;
     int x;

     (*count)++;
     x = *count;

    printf("Your new data will have an ID of %d\n",x);
    a[x].aa = x;

    b = (struct lottery *)realloc(a, x * sizeof(struct lottery));
    if (b == NULL) {
        printf("Memory could not be allocated for your new input.Program will now exit...\n");
        exit("0");
    }

    a = b;

    printf("What is the date of your new draw?\n");
    scanf("%d/%d/%d", &a[x].date1.day, &a[x].date1.month, &a[x].date1.year);
    printf("Now please insert the 5 non-joker numbers\n");
    scanf("%d%d%d%d%d", &a[x].n1, &a[x].n2, &a[x].n3, &a[x].n4, &a[x].n5);
    printf("What is the 'Joker' number of this draw?\n");
    scanf("%d", &a[x].joker);
    printf("Your input is now complete.");
}

I am writing protection for some lottery files. I have this problem in my function that adds more data to the lottery array. When it xcontains 1989, my call reallocreturns NULL. I installed xas 1985, but I icould add 4 more entries to the array, but whenever x- 1989, it still returns NULL. My question is: is something wrong with the code, or am I still running out of memory?

+4
source share
3 answers

realloc null, , . , . , , . malloc(), , - . , , , .

+2

:

C , x * sizeof(thing) x-1. x .

-, a = b a, array, , ...

0

realloc , array , reallocation main .

You also down reallocateto 0-size, probably not what you want, use x+1as the number of records in the redistribution. Also, before redistributing, you get an index xthat is undefined because the size of the redistribution is equal x-1, so move the row a[x].aa = xafter the redistribution.

Also, please initialize your variables (e.g., counter).

0
source

Source: https://habr.com/ru/post/1667372/


All Articles