Solved

Beginner's question

Posted on 2000-04-13
1
229 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
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 opening and writing to files 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.

726 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