Question

My requirement is to have a dynamic memory allocation for the char * variable I am creatigng so that when the while loop in my applciation reads data, the memory allocation should increase accordinly, But what happens when I run the code is i get the erroe,

*** glibc detected *** ./rpp: realloc(): invalid next size: 0x0000000001376010 ***

I found many questions posted on this topic here in stackoverflow through this google search (https://www.google.com/search?client=ubuntu&channel=fs&q=realloc%28%29%3A+invalid+next+size%3A+0x0000000002401010+&ie=utf-8&oe=utf-8#channel=fs&q=realloc%28%29:+invalid+next+size:+) but non helped. I would really appreaciate if you experts would help me on this one to fix this error as I am now clueless on how to fix this. Following id the function which gives me the error.

int execScanNetowrk(){

    FILE *fp;
    int status;
    char path[1035];
    char *pathFull;
    pathFull = (char*)malloc(sizeof(path));


    /* Open the command for reading. */
    fp = popen("nmap -sP -oG - 192.168.1.0/24", "r");

    if (fp == NULL) {
            printf("Failed to run command\n" );
            exit;
    }

    /* Read the output a line at a time - output it. path stores each line of data per iteration*/
    while (fgets(path, sizeof(path)-1, fp) != NULL) {

        pathFull = (char*)realloc(pathFull, sizeof(path));//increase memory allocation
        strcat(pathFull,path);//concatenate char * with the read data           

    }

    printf("%s\n", a);  
    /* close */
    pclose(fp);
    free(a);
    return 0;

}

Thank you very much :)

Was it helpful?

Solution

The general technique for fixing this kind of problem is to apply valgrind which will give you more detailed error messages pointing right at the problem.

Your specific problem is here:

    pathFull = (char*)realloc(pathFull, sizeof(path));//increase memory allocation

The second argument to realloc is the total number of bytes you want, not the number of bytes by which to increase the allocation. You need to track the current size of pathFull and do realloc(pathFull, oldSize + sizeof(path)) or similar.

Do you really want to read the entire nmap output into memory before processing it at all, or is your actual goal to read entire lines into memory before processing them? Your code is trying to do the former, but you probably meant to do the latter, in which case getline may be easier to use than mucking about with fgets.

Obligatory nitpick: when coding in C do not cast the return value of malloc nor realloc. It is unnecessary and may prevent the compiler from noticing when you forget to #include <stdlib.h>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top