Search code examples
cvectorrealloc

Realloc: invalid next size in dynamic vector of structs


I'm trying to make this code work, but I cannot see why it crashes. It is supposed to read data from a file, and put it sorted (insertion sort) in a vector. proc is a vector of Process_t, proc.name is a char[10], proc[0] is inserted before (hard coded) and num_proc == 1. The first register of the file is catched properly, but then it crashes (just in the realloc()).

    size = 1
    while(size > 0)
    {
        // Read a process from the config file and add to the vector in a sorted way
        printf("%d\n", num_proc);
        proc = realloc(proc, sizeof(Process_t)*num_proc);
        printf("%d\n", num_proc);

        size = fscanf(cfgfd, "%hhd %s\n", &hwmodid, buf);
        printf("%d %d %s\n", num_proc, hwmodid, buf);

        i = num_proc-1;
        while(i > 1 && proc[i].hwmodid > hwmodid)
        {
            strcpy(proc[i+1].name, proc[i].name);
            proc[i+1].hwmodid = proc[i].hwmodid;
            proc[i+1].pid = proc[i].pid;
            proc[i+1].fiforfd = proc[i].fiforfd;
            proc[i+1].fifowfd = proc[i].fifowfd;
            proc[i+1].paused = proc[i].paused;
            --i;
        }
        strcpy(proc[i+1].name, buf);
        proc[i+1].hwmodid = hwmodid;
        proc[i+1].pid = -1;
        proc[i+1].fiforfd = -1; 
        proc[i+1].fifowfd = -1;
        proc[i+1].paused = 0;
        ++num_proc;

        printf("%d %s %d %d %d %d %d\n", i, proc[num_proc-1].name, proc[num_proc-1].hwmodid, proc[num_proc-1].pid, proc[num_proc-1].fiforfd, proc[num_proc-1].fifowfd, proc[num_proc-1].paused);
    }

Solution

  • I just realized I missed a +1 when reallocating. I was allocating for what I already had (at first I had 1, and was allocating for 1 and inserting 1). The first element of the vector inserted dinamically was put by luck. Stupid mistakes that are difficult to find.