2


I wrote a little function to return a string made from the input given to the program, it worked fine until i traded constant size for dynamic memory allocation.
After i tested with a few printf() it looks like the program crashes when realloc() is called.
Am i doing something wrong with realloc(), or is it something else?

char* get_line()
{
    size_t ptr_pos = 0, size = 50;
    int c;
    char* line = malloc(size * sizeof *line);
    char* temp;

    while((c = getchar()) != EOF)
    {
        if(++ptr_pos >= size)
        {
            size += 50;
            temp = realloc(line, size * sizeof *line); // The program crashes on this intruction.

            if(temp != NULL)
            {
                line = temp;
                printf("Reallocation success.\n");
            }
            else
            {
                printf("Reallocation error.\n");
                free(line);
                exit(1);
            }
        }

        *line++ = c;
        if(c == '\n')
            break;
    }
    if(ptr_pos == 0)
        return NULL;
    *line = '\0';

    return line - ptr_pos;
}


Thanks for your help.

aurelienC
  • 1,113
  • 3
  • 12
  • 22
  • `malloc()` and `realloc()` return `void *`. You are using them directly as `char *`. Convert them explicitly. – Pawan Dec 06 '15 at 13:49
  • 3
    You might like to replace `*line++ = c;` by `line[ptr_pos - 1] = c;`. – alk Dec 06 '15 at 13:49
  • 1
    @Pawan: This is *not* necessary, nor recommend in C. C is not C++. – alk Dec 06 '15 at 13:49
  • 1
    @Pawan [c - Do I cast the result of malloc? - Stack Overflow](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) - no. – MikeCAT Dec 06 '15 at 14:01
  • @alk "You might like to replace `*line++ = c;` by `line[ptr_pos - 1] = c;`" . Now that i have read rici's answer i understand why this will suppress the mistake, good point. – aurelienC Dec 06 '15 at 17:32

1 Answers1

4

When you call realloc, you must give it the address of the beginning of the allocated memory, the same address as was originally returned by malloc. The same is true of free.

But you are modifying the value of line, so it is no longer pointing to the beginning of the block when realloc is called.

That is Undefined Behaviour, so a segfault is definitely possible.

rici
  • 234,347
  • 28
  • 237
  • 341