Search code examples
cmallocreallocsigabrt

Error on realloc : corrupted size vs. prev_size


I'm coding in C. The goal of my algorithm is to double each char c we find in an array str. I have to run a few tests, for the first test I call doubleChar("~/fichier.txt", '~') and it works fine, but my second test is doubleChar("une commande # commentaire", '#') and I get the error from the title. When i tried to debug it, the error was on the realloc line.

In debugger I get this error:

Program Received signal SIGABRT Stack trace is available in the 'Call Stack' tab

Any idea why?

Here's my code:

    char * doubleChar(const char *str, char c){
assert(str!=NULL);
    char *newString=malloc(sizeof(str) * sizeof(char));
    int a = 0;
    while(str[a] != '\0'){
        newString[a]=str[a];
        a++;
    }
    newString[a]='\0';
    int i = 0;
    while(newString[i] != '\0'){
        if(newString[i] == c){
            newString = (char *)realloc(newString, stringLength(newString)*sizeof(char) + sizeof(char));
            for(int j=stringLength(newString)+1; j>i; j--){
                newString[j]=newString[j-1];
            }
            i++; //we add 1 to i so we don't find the char we just added
        }
        i++;
    }
    return newString;
}

Solution

  • char *newString=malloc(sizeof(str) * sizeof(char));
    

    Since str is a const char *, the sizeof(str) is how many bytes a const char * takes on your platform. That's not what you want. What you want to pass to malloc is the length of the string you want to store, making sure to leave an extra byte for the terminating zero. In this case, that's (strlen(str) + 1).

    newString = (char *)realloc(newString, stringLength(newString)*sizeof(char) + sizeof(char));
    

    This is probably also wrong. You need (strlen(newString) + 2) to leave one byte for the newly-added character and one byte for the zero terminator. It's hard to be sure though because I can't tell what your stringLength function does.

    Also, sizeof(char) is, by definition, one. The sizeof function returns the size in characters.

    It's much easier to understand strlen(newString) + 2 than stringLength(newString)*sizeof(char) + sizeof(char) because strlen is a standard function and sizeof(char) is verbose and ugly. So I'd strongly suggest changing this to strlen(newString) + 2.