Search code examples
carrayspointersmemoryrealloc

"realloc(): invalid next size" after multiple successful runs


I keep getting this error after the array has already stored multiple lines from user input, which tells me that it's probably corrupted memory due to the line:

    poemArray = (char **)realloc(poemArray, count + 1);

Any idea what I'm doing wrong? A specific solution would be much appreciated!

    line = (char *)malloc(MaxLineLen);

    fgets(line, MaxLineLen, stdin);
    /*Get current line from user input*/
    if(count == 0)
    {
        poemArray = malloc(sizeof(char *));
        printf("1\n");
    }
    if(line[0]  == '.'){
        break;
    }
    line = (char *)realloc(line, strlen(line));

    printf("2\n");

    if(count != 0)
    {
        poemArray = (char **)realloc(poemArray, count + 1);
    }
    poemArray[count] = line;

    ++count;

Solution

  • This

    poemArray = (char **)realloc(poemArray, count + 1);
    

    should actualy be

    poemArray = realloc(poemArray, (count + 1) * sizeof(char *));
    

    Also, this

    line = (char *)realloc(line, strlen(line));
    

    should probably be

    line = realloc(line, strlen(line) + 1);
    

    It is also unclear why you are doing the initial malloc for poemArray before the potential break. That way you might end up with poemArray as an uninitialized array of size 1. What is the point of having it uninitialized?


    Additionally, note that realloc is designed to properly handle null pointer as its first argument. In such cases realloc is essentially equivalent to malloc. By taking advantage of this feature of realloc you can eliminate dedicated processing for count == 0 state, thus ending up with much more compact and elegant code.

    P.S. Why some calls to malloc include an explicit cast, while others don't? In any case, there's no point in casing the results of memory allocation functions in C.