Search code examples
cmallocrealloc

pointer being realloced was not allocated


I am trying to dynamically allocate an array of structs but whenever I run the program I keep getting: a.out(6487,0x7fff7ecb8300) malloc: * error for object 0x7fff6f670000: pointer being realloc'd was not allocated * set a breakpoint in malloc_error_break to debug

struct node {
    char course[25];
    char category[20];
    char prereq[50];
    char notes[50];
};



int main(int argc, char* argv[])
{
    FILE *fp;
    char *filename = argv[1];
    char *token;

    char buffer[100];
    char *del = ",\n";
    int num = 5, i = 0, j =0, count = 0;
    struct node *d = malloc(num * sizeof(struct node));
    char** complete = malloc(num * sizeof(char*));
    printf("%s\n", filename);


    if( (fp = fopen(filename, "r")) == NULL )
    {
        printf("unable to open %s\n", filename);
        exit(1);
    }
    while(fgets(buffer, sizeof(buffer), fp) != NULL)
    {

        if(count == num)
        {
            num = num + 5;
            struct node *d = realloc(d, sizeof(d)*num);
            printf("Reallocating\n");
        }  
        token = strtok(buffer, del);

        if(strncmp(token, "#", 1) != 0)
        {   

            strcpy(d[count].course, token);
            printf("%s\n", d[count].course);
            strcpy(d[count].category, strtok(NULL, del));
            printf("%s\n", d[count].category);
            strcpy(d[count].prereq, strtok(NULL, del));
            printf("%s\n", d[count].prereq);
            strcpy(d[count].notes, strtok(NULL, del));
            printf("%s\n", d[count].notes);
            count++;
        }


    }

Solution

  • struct node *d = realloc(d, sizeof(d)*num);
    

    You're declaring a new d variable which shadows the previous one, and feed its yet-uninitialized value to realloc.

    You need to do this :

    struct node *newD = realloc(d, num * sizeof *d);
    if(!newD) {
        // Allocation failure, do something about it and break out
    } /* else */
    d = newD;
    

    Also note that I corrected the sizeof, which measured the size of the pointer, not the pointee's.