Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

what is segmentation fault

Status
Not open for further replies.

krishna_1980

Junior Member level 3
Joined
Jan 4, 2006
Messages
25
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Activity points
1,457
the following code is giving runtime error as "segmentation fault".why?

char *str;
fp=fopen("f1.txt","r");
fgets(str,10,fp);
puts(str);

but the following code is working.................................................

char *str;
fp=fopen("f1.txt","r");
fgets(str,10,fp);
for(i=0;i<10;i++)
printf("%c",*(str+i));
 

I dont know much about C++ but i saw something in their functions:

This is an example for puts function.
Code:
* puts example : hello world! */
#include <stdio.h>

int main ()
{
  char string [] = "Hello world!";
  puts (string);
}

In your code you have defined str as a pointer as i can understand,whereas in the example it is not a pointer,just an aray.try using an array,not a pointer

I ussually code in Fortran and i get the error "Segmentation fault" when i have trouble with memory access,for example if i have defined an array of size 15 and i am trying to access Array[17].then i get a segmentation fault.
 

You declared just the pointer to a memory space, but, did not declare a variable to store the read string, which is the problem.

Added after 7 minutes:

The segmentation fault is caused by accessing a memory space called a segment that is not allowed to be accessed from some other segment.
 

Hi,

The problem is, it is required to strore the end of string "\0".

While printing using the 2nd method, ie using loop, you are exactly printing just the number of characters you read and printing. This will work fine. But during first method, puts(), which just prints the string by reading character by character and look for end of string, ie '\0' which is not stored in the string while reading. It is required to explicitly store "EOS" end-of-string otherwise you will have to use the first method.

Kars
 

I think string constant automatically terminated by '\0', so, I think it is OK.
 

Hi,
Great. it is required to allocate memory for "str" before using it.

Kars.
 

No, the memory for the pointer was allocated, but it was never initialized with the address of a valid char location. In this case, the values in the memory that was allocated to it is a value that caused a segmentation error.
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top