Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

fgets question 1

Status
Not open for further replies.

Bangieff

Technical User
Feb 12, 2001
52
BG
Hi all
Here is the situation:
I need a program that reads information from stdin and for example write it to stdout (the second part is not exactly the same but it's not important right now ;) ). And that's what I wrote:

#include <stdio.h>

main()
{
char *str;
while (1)
{
if (fgets(str,124,stdin)!=NULL
{
printf(&quot;->%s\n&quot;,str);
}
}
}

and when I run: tail xxx.txt | ./a.out
I'm getting segmentation fault. I just hate this error ;)
Can anyone tell me where the problem is
Thanks in advance ;)
 
Yes, will get segmentation fault.

You have declared a pointer variable str, you are not allocated any space for that but your are reading a maximum of 124 characters for the file and storing to the unallocated pointer variable.

change the
char *str; statement to
char str[125]; or
keep char *str as it is and allocate memory for that before reading for the file.

put str = (char *) malloc( 125 * sizeof(char));
before the while statement and before the main functions }
put free(str);

Regards
Maniraja S



 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top