Reputation: 872
I just want to know why this piece of code giving me segfault.
if(argc < 2){
printf("\n Please mention the file name");
exit(1);
}
FILE* fp;
if((fp = fopen(argv[1],"r")) == NULL){
printf("\n can't open file");
exit(1);
}
char* str;
fgets(str,80,fp);
printf("\n this is the output %s",str);
If I declare str as char str[100],then it works fine.
Upvotes: 1
Views: 178
Reputation: 1763
char* str;
declares a pointer to char, but doesn't reserve any space for the characters themselves. Also since you haven't initialized it, it is pointing at some random place in memory.
Then fgets(str, 80, fp)
says to take 80 characters from the file and store them starting at the pointed location. Since (most likely) your program doesn't own that location, you get a segfault.
char str[100];
reserves space for 100 characters on the stack as an array, and you can use str
as a pointer to the start of this array. Your program is allowed to do whatver it wants with this memory so there is no segfault when you do fgets
. Note that if your array is too short, then you may still have problems, though not necessarily segfaults.
Upvotes: 0
Reputation: 178055
char* str
is an uninitialized pointer. fgets
writes to the memory pointed to by this pointer, which can be anywhere. Declaring actual storage with str[100]
provides 100 bytes of valid memory to write.
Upvotes: 2
Reputation: 14034
You're not allocating any memory; you're just declaring a char *
. Either char str[100]
will work, or:
char *str = malloc(100);
That will allocate memory for your string. Otherwise, you're just reading from fgets()
into memory that isn't yours, and causing a segmentation fault.
If you do this, make sure to call free()
on it after you're done with it.
Upvotes: 3