[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Beginner's question

Posted on 2000-04-13
1
Medium Priority
?
237 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 150 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.

831 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