C code Error: free(): invalid next size (fast):

Posted by user1436057 on Stack Overflow See other posts from Stack Overflow or by user1436057
Published on 2012-06-04T21:49:48Z Indexed on 2012/06/04 22:40 UTC
Read the original article Hit count: 108

Filed under:
|
|

I got an error from my code, but I'm not sure where to fix it.

Here's the explanation of what my code does:

I'm writing some code that will read an input file and store each line as an object (char type) in an array. The first line of the input file is a number. This number tells me how many lines that I should read and store in the array. Here's my code:

int main(int argc, char *argv[]){
    FILE *fp; 
    char **path;
    int num, i;
    ...
    /*after reading the first line and store the number value in num*/
    path = malloc(num *sizeof(char));

    i=0;
    while (!feof(fp)) {
        char buffer[500]; 
        int length = 0;

        for (ch = fgetc(fp); ch != EOF && ch != '\n'; ch = fgetc(fp)) {
            buffer[length++] = ch;
        }

        if(ch == '\n' && ch!= EOF){
            buffer[length] = '\0';
            path[i] = malloc(strlen(buffer)+1);
            strcpy(path[i], buffer);
            i++;
    }
    }

    ...
    free(path);
}

After running the code, I get this

*** glibc detected *** free(): invalid next size (fast): 

I have searched around and know this is malloc/free error, but I don't exactly know to fix it. Any help would be great. Thanks!

© Stack Overflow or respective owner

Related posts about c

    Related posts about arrays