Solved

Beginner's question

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

The curse of the end user strikes again      

You’ve updated all your end user’s email signatures. Hooray! But guess what? They’re playing around with the HTML, adding stupid taglines and ruining the imagery. Find out how you can save your signatures from end users today.

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…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
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.
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.

863 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

23 Experts available now in Live!

Get 1:1 Help Now