segmentation error

Hello,I am new to C in Linux/ubuntu. I write a fragment with segmentation error.I can't find the point.Can somebody help me ?By the way,I have some other question about the function getc.Please tell me how to use it,and how to initialize a char pointer. Thank you in advance.My code is below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<stdio.h>

int main()
{
 FILE *fp; 
 char *s=NULL;
 fp = fopen("test.txt","r+");
 if((s= fgets(s,40,fp))!=NULL)
    printf("%s",s);
 else
    printf("Fail to open file.\n");
 fclose(fp);
 exit(0);
}
Hi Wandy,

The first parameter you pass to fgets must be a valid string. In your case you are trying to write over char*s=NULL with fgets which will cause segmentation fault.

You can try

char mystring [100];

instead of

char *s=NULL;


Last edited on
Here I want to use the pointer and I initialize it with the NULL.Is it right?Or can you tell me initialize a pointer? Thank you~~
Ok, there is no problem in initializing the pointer. The problem is that this pointer points to NULL. Your pointer needs to point to a valid area in the memory.

For example:

1
2
char *s=NULL;
*s = 'z'; // write z to the point where s points. Where does s point? 


This code will crash, because you are trying to write to the NULL location.

There are two simple alternatives, either you allocate a memory area statically by creating an array, or dynamically reserving a memory area with new operator.

When you define an array with a size, char mystring [100],that means you are creating a pointer of char type with the name mystring and this pointer points to the start of a memory area of 100 chars. That way the compiler knows what to do.

Or you can either use the new operator as such:
1
2
char * s;
s = new char [50];  

Here you have the valid pointer which points to the start of an allocated area with 50 char size.
You can read the tutorial for dynamic memory allocation:
http://www.cplusplus.com/doc/tutorial/dynamic/
Last edited on
Got it !!Thank you so much~~~
You're welcome.

I forgot to mention that you need to give back the memory you allocated after you are finished with it(with delete operator). You can also find info about that in the tutorial.
Last edited on
Thank you ,ZephyrTR.So kind of you~
Do some research on "GDB" - GNU Debugger. It would point you to the exact line. Starting off could take a couple minutes, but once you get used to it, it's fairly trivial.
Topic archived. No new replies allowed.