Solved

Beginner's question

Posted on 2000-04-13
1
224 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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

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…
Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
The goal of this video is to provide viewers with basic examples to understand and use pointers in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

743 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now