Home > front end >  realloc() invalid next size after second time
realloc() invalid next size after second time

Time:10-07

I was building an FCFS scheduler as a school project when I had this problem: reallocating for the first time would work fine, but at the second try the program would crash giving the error "realloc(): invalid next size". Here's the code.

typedef struct Process {
    unsigned int id, bt, wt, tat;
} Process; 

That's how the array is created:

size_t n;
    printf("\nQuanti processi vuoi creare? >> ");
    scanf("%lu", &n);

    Process *p = malloc(sizeof(Process)*n);
    if(p == NULL) {
        printf("Allocazione della memoria fallita.\n");
        return 0;
    }

The purpose of the function below is to add space to fit one more Process.

void increase(Process **p, size_t *n) {
    *p = realloc(*p, sizeof(*p) sizeof(Process));
    

    *n  = 1;
}

The function "increase" is then called in a switch case where I ask the user if he wants to add another process.

int op;
    do {
        printf("Vuoi aggiungere un processo? (0/1) >> ");
        scanf("%d", &op);

        if(op) {
            increase(&p, &n);
            initProcess(p, n-1);

            printStatus(p, n);
        }
    } while(op);

Just for clearance, I'll put the other 2 functions even if they're not that much relevant.

void initProcess(Process p[], size_t n) {
    p[n].id = n;
    p[n].bt = rand() % 15   1;
    p[n].wt = p[n-1].bt   p[n-1].wt;
    p[n].tat = p[n].bt   p[n].wt;
}
void printStatus(Process p[], size_t n) {
    size_t i;
    printf("PID\tBurst Time\tWaiting Time\tTurn-around Time\n");
    for(i = 0; i < n; i  ) {
        printf("%u  \t%u\t\t%u  \t\t%u\n", p[i].id, p[i].bt, p[i].wt, p[i].tat);
    }

    printf("\nMedia   %.2f   \t%.2f\t\t%.2f\n", avgCalc(p, n, 0), avgCalc(p, n, 1), avgCalc(p, n, 2));
}

Can't figure out why it doesn't work.

CodePudding user response:

sizeof(*p) is size of a pointer, not of the allocation.

You cannot portably get the size of the allocation, so you have to keep track of it yourself.

So you are accessing outside the allocation, since you're not actually resizing.

Use (*n 1)*sizeof(Process) instead, since you are actually keeping track of the intended element count.

  •  Tags:  
  • c
  • Related