user1681378
user1681378

Reputation: 19

Realloc consistently fails (in C)

Realloc consistently fails after I add 25 characters.

The error:

Inconsistency detected by ld.so: dl-minimal.c: 116: realloc: Assertion `ptr == alloc_last_block' failed!

char** linePtr = getLinePtr(block, y);
char* tmpPtr = realloc(*linePtr, (strlen(*linePtr) + 1) * sizeof(char));
if (tmpPtr != NULL) {
    *linePtr = tmpPtr;
    strinsert(tmpPtr, ch, x);
}

I check the variables right before and everything seems fine. *linePtr points to a string of 24 characters and strlen(*linePtr) returns 24. The address returned by realloc is always the same.

There is no number hard-coded so I have no idea why it always fail after the same number of characters.

*linePtr was 1 just one byte at the beginning and I am reallocating one extra byte every time for now.

Edit:

char** getLinePtr(Block* block, int y)
{
    assert(y >= block->start && y <= block->start + block->nb_lines);

    if (y == block->start + block->nb_lines) {
        block->lines = realloc(block->lines, (block->nb_lines + 1) * sizeof(char*));
        *(block->lines + block->nb_lines) = malloc(sizeof(char));
        block->nb_lines++;
    }
    return block->lines + block->nb_lines - 1;
}

Edit2:

By pasting the code I realise there is a bug in getLinePtr: It returns the last line instead of the one asked (using y), but it should not change anything to this bug. And only the first line is used.

Upvotes: 1

Views: 798

Answers (2)

user1681378
user1681378

Reputation: 19

The problem was that I needed to reallocate (strlen(*linePtr) + 2) instead of (strlen(*linePtr) + 1).

strlen returns the size of the string without the terminating null character. So I need to add 1 for it and I need to add 1 for the character to be added right after.

Thanks to Daniel Fisher for the hint.

Upvotes: 0

Mark Wilkins
Mark Wilkins

Reputation: 41262

It seems likely that the problem is that the pointer that is being passed to realloc is not a pointer that was returned by realloc or malloc. There are several pieces missing from the shown code to be able to know that for sure. But you should verify that getLinePtr is returning a "pointer to the allocated pointer" (I'm not saying that is a good way to do it, but that is how it is being used in the shown code).

Upvotes: 3

Related Questions