views:

106

answers:

1

I have a problem with realloc function:

*** glibc detected *** realloc(): invalid next size:

Here is the relevant part of code:

    char* pathfile = NULL;
    int tcpargc=6;
    char *tcpargv[tcpargc];
    int it;
    for (it = 0;it < tcpargc;it++)
       tcpargv[it] = NULL;
    ...
    while (1) {
    ...
    if (pathfile == NULL)
       pathfile=(char*)malloc((strlen(RAMDIR)+strlen(tempfilename)+7)*sizeof(char));
    else {
    if ((tmp=(char*)realloc(pathfile,(strlen(RAMDIR)+strlen(tempfilename)+7)*sizeof(char))) == NULL)
    {
 printf("ERROR: realloc failed");
        free(pathfile);
    }
    else
        pathfile = tmp;
    }
    ...
    if (tcpargv[4] == NULL)
    tcpargv[4]=(char*)malloc((strlen("--infile=")+strlen(pathfile)+1)*sizeof(char));
    else {
    if ((tmp = (char*)realloc(tcpargv[4],strlen("--infile=")+strlen(pathfile)+1)*sizeof(char)))   == NULL){
    printf("ERROR: realloc failed");
    free(tcpargv[4]);
    }
    else
    tcpargv[4] = tmp;
    } 
    ...    
    }

I have checked it again and again but I could not find the error.
Thanks for you help.

+1  A: 

That error indicates that your code is probably overwriting bookkeeping data used by the glibc memory allocation subsystem. As Michael Mior suggested in his comment, try running your code under Valgrind -- it's quite good at finding such memory corruption errors.

llasram
Valgrind was a very good tip. However i have a new problem now when i am using valgrind my program is working fine unless i get the double free or corruption (out).
Yassine
@Yassine How is that a problem? -- perhaps I don't understand your meaning. Valgrind runs your program via an emulation layer which intercepts and reports invalid memory accesses. Instead of glibc errors or random segfaults you get valgrind error logs showing where you need to fix your code. Fix your memory errors and the code will run fine both under valgrind and not.
llasram
the problem is that when i am using valgrind my program works well i see the valgrind reports but the program still working doing exactly what i want. But when i start the program without valgrind reports it does not work after when loop an error occurs indicating double free or corruption (out).
Yassine
Thanks all right now :)
Yassine