2

I have this function:

static void unfoldLines(char **pbuff, char **lines, int foldCount) {
    int i, j;

    for(i = 1; i <= foldCount; i++) {
        removeEOL(lines[i]);
        for(j = 0; j < strlen(lines[i]); j++) {
            while(isspace(lines[i][j])) {
                lines[i]++;
            }
        }
    }

    lines[1] = realloc(lines[1], sizeof(char) * (strlen(lines[1]) +
                strlen(lines[2]) + 1));
    exit(0);
}

lines and it's pointers has been malloced in a previous function. When I try to realloc lines[1], I get this error:

malloc: *** error for object 0x7fcec0404fe1: pointer being realloc'd was not allocated

I know it has been malloced, so why can't it be realloced in this function?

9
  • Because it increments the pointer. Commented Jan 19, 2016 at 2:56
  • Crap! Should I a) not increment the pointer or b) is there a way around this? Commented Jan 19, 2016 at 2:57
  • It moves each character. Commented Jan 19, 2016 at 2:59
  • I understand that incrementing the pointer changes the address, making me able to realloc/free it. I increment the pointer to remove any leading whitespace. What should I do here? Commented Jan 19, 2016 at 3:01
  • 1
    @MortalMan remove leading whitespaces Commented Jan 19, 2016 at 3:14

1 Answer 1

2

lines[1] gets incremented in the for-loop. You should keep the original pointer(s) that are returned from malloc() and use those with realloc().

Also, realloc() can fail, so you should store the return value of realloc() in a temporary pointer, and only on success transfer that to the original pointer.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.