Solved

Beginner's question

Posted on 2000-04-13
1
228 Views
Last Modified: 2010-04-15
I'm trying to read something from stdin. Why would this segmentation fault?

#include <stdio.h>
#include <stdlib.h>

#define N 100

int main( void )
{
        char *buf = (char *)malloc(N);
        char *all;

        int i = 0;

        while(fgets(buf,N,stdin) != NULL)
        {
                i += N;
                all = realloc(all,i);

                if(all == NULL)
                {
                        printf("Cannot allocate more mem\n");
                        return;
                }

                strcat(all,buf);
        }

        printf("%s\n", all);

        free(all);
        free(buf);
}
0
Comment
Question by:m00
1 Comment
 
LVL 16

Accepted Solution

by:
imladris earned 50 total points
ID: 2713454
Realloc will change the size of an allocated memory block. Additionally it will allocate a memory block (in the same way malloc does) if the first argument is NULL. In other words, realloc expects the first argument to be either NULL, or a valid pointer to a memory block.

However in your code, all is declared on the stack and is not initialized. So it can come up with garbage in it. This is presumably what occurred. If realloc gets a garbage filled all, it will assume it is a valid memory block and go about trying to change its size. But since it isn't a valid memory block, you get a segmentation fault.
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question