Unexplained segmentation fault


 
Thread Tools Search this Thread
Top Forums Programming Unexplained segmentation fault
# 1  
Old 03-25-2011
Unexplained segmentation fault

Hi, The following code reads 20 characters from one file and writes them (appends them) to the other file. The code works in Turbo C++ on windows but it shows segmentation fault on Linux. I am using Ubuntu 10.10 and gcc compiler.
Please tell me where I was wrong.

Code:
#include<stdio.h> 
 
void main() 
{ 
char* buf; 
char c; 
FILE * fp; 
FILE * fp2; 
int k; 
fp=fopen("sample","r"); 
fp2=fopen("sample1","a"); 
buf=fgets(buf,20,fp); 
while(buf!=NULL) 
{ 
k=fputs(buf,fp2); 
printf("%s\n",buf); 
buf=fgets(buf,20,fp); 
} 
 
}

Thanks for your help.Smilie
# 2  
Old 03-25-2011
Code:
char *buf;

This doesn't create memory for you. All a pointer is is an integer describing where memory is. And just like an uninitialized integer, an uninitialized pointer can be anything at all. So you could be trying to use any memory at all, which, in DOS, could mean accidentally overwriting bits of your operating system and hanging the computer or worse... In Linux though, your process resides in its own protected memory space, and if you try to use memory you didn't ask for, it can tell the difference and kills it.

IOW, this code was always wrong. It didn't crash in DOS mode only because DOS mode is physically incapable of detecting that problem. If you compiled this as a 32-bit Windows program it'd crash too.

If you want something that actually has memory, you can declare it as a buffer on the stack:
Code:
char buf[20];

or you can give the pointer something to point to like
Code:
char *buf=malloc(20);

...
// before main returns.  Especially important in DOS!
free(buf);

malloc() needs malloc.h in Turbo C++, or stdlib.h for compilers that aren't 30 years out of date.

The rest of your code looks fine. Smilie You should check if fp and fp2 are NULL though -- if they didn't succeed in opening for some reason, your program goes ahead and tries to use them anyway, which will crash too -- or at least really ought to crash.

It might be better to program in Linux than DOS. Linux is a less forgiving environment, you'll catch some mistakes immediately which in DOS might not do anything immediately but could cause very weird side-effects later. Linux is even capable of detecting which line it crashed in if you compile with -ggdb and run the program with gdb...

Last edited by Corona688; 03-25-2011 at 04:13 PM..
This User Gave Thanks to Corona688 For This Post:
# 3  
Old 03-25-2011
Hi.

Sometimes lint-like tools can catch these errors. For example, on Debian GNU/Linux, there is a utility splint. The output from running it on your code is:
Code:
% splint t1.c
Splint 3.1.2 --- 23 Aug 2008

t1.c:4:1: Function main declared to return void, should return int
  The function main does not match the expected type. (Use -maintype to inhibit
  warning)
t1.c: (in function main)
t1.c:13:16: Unallocated storage buf passed as out parameter to fgets: buf
  An rvalue is used that may not be initialized to a value on some execution
  path. (Use -usedef to inhibit warning)
t1.c:13:25: Possibly null storage fp passed as non-null param: fgets (..., fp)
  A possibly null pointer is passed as a parameter corresponding to a formal
  parameter with no /*@null@*/ annotation.  If NULL may be used for this
  parameter, add a /*@null@*/ annotation to the function parameter declaration.
  (Use -nullpass to inhibit warning)
   t1.c:11:8: Storage fp may become null
t1.c:16:23: Possibly null storage fp2 passed as non-null param:
               fputs (..., fp2)
   t1.c:12:9: Storage fp2 may become null
t1.c:7:8: Variable c declared but not used
  A variable is declared but never used. Use /*@unused@*/ in front of
  declaration to suppress message. (Use -varuse to inhibit warning)

Finished checking --- 5 code warnings

Best wishes ... cheers, drl
This User Gave Thanks to drl For This Post:
# 4  
Old 03-25-2011
Quote:
Originally Posted by drl
Sometimes lint-like tools can catch these errors.
Adding -Wall to gcc's commandline can cause it to warn you about a lot of them too.
This User Gave Thanks to Corona688 For This Post:
# 5  
Old 03-26-2011
Thank you all for replying. Problem is solved. used malloc(20). Thanks for suggesting better debugging methods.
# 6  
Old 03-26-2011
Quote:
Originally Posted by Corona688
Code:
char *buf;

This doesn't create memory for you. All a pointer is is an integer describing where memory is. ...

Arrgh! No! Not that! Smilie

Seriously, in order to be perfectly clear: while a pointer may be an integer-type value, a pointer is NOT an int, nor a long, nor an unsigned int or unsigned long. A pointer is a pointer. Just because it might be the same number of bytes as a some specfic integer-type variable for whatever architecture you're coding in, that doesn't mean that relationship will hold for other architectures.

Along the same lines, size_t is size_t, NOT unsigned int.

If you screw that up and get it ingrained into your programming practices, when you move to another architecture (Can you say "64 bits"? Thank you, I knew you could!), you'll have some serious problems.
This User Gave Thanks to achenle For This Post:
# 7  
Old 03-26-2011
Quote:
Originally Posted by achenle
Seriously, in order to be perfectly clear: while a pointer may be an integer-type value, a pointer is NOT an int, nor a long, nor an unsigned int or unsigned long. A pointer is a pointer. Just because it might be the same number of bytes as a some specfic integer-type variable for whatever architecture you're coding in, that doesn't mean that relationship will hold for other architectures.
And nowhere is this more true than Borland Turbo C++, which has several kinds of pointers, of differing sizes, due to 16-bit segment weirdness.

Last edited by Corona688; 03-26-2011 at 04:32 PM..
This User Gave Thanks to Corona688 For This Post:
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Programming

C. To segmentation fault or not to segmentation fault, that is the question.

Oddities with gcc, 2.95.3 for the AMIGA and 4.2.1 for MY current OSX 10.14.1... I am creating a basic calculator for the AMIGA ADE *NIX emulator in C as it does not have one. Below are two very condensed snippets of which I have added the results inside the each code section. IMPORTANT!... (11 Replies)
Discussion started by: wisecracker
11 Replies

2. Solaris

Segmentation fault

Hi Guys, I just installed and booted a zone called testzone. When I logged in remotely and tried changing to root user I get this error: "Segmentation fault" Can someone please help me resolve this? Thanks alot (2 Replies)
Discussion started by: cjashu
2 Replies

3. Homework & Coursework Questions

Segmentation Fault

this is a network programming code to run a rock paper scissors in a client and server. I completed it and it was working without any error. After I added the findWinner function to the server code it starts giving me segmentation fault. -the segmentation fault is fixed Current problem -Also... (3 Replies)
Discussion started by: femchi
3 Replies

4. Programming

Using gdb, ignore beginning segmentation fault until reproduce environment segmentation fault

I use a binary name (ie polo) it gets some parameter , so for debugging normally i do this : i wrote script for watchdog my app (polo) and check every second if it's not running then start it , the problem is , if my app , remain in state of segmentation fault for a while (ie 15 ... (6 Replies)
Discussion started by: pooyair
6 Replies

5. Programming

segmentation fault

Hi, I am having this segmentation fault not in the following program, bt. in my lab program . My lab program is horrible long so cannot post it here bt. I am using the following logic in my program which is giving the segmentation fault. Bt. if I run this sample program as it is it dosen't give... (3 Replies)
Discussion started by: mind@work
3 Replies

6. Programming

Why not a segmentation fault??

Hi, Why I don't receive a segmentation fault in the following sample. int main(void) { char buff; sprintf(buff,"Hello world"); printf("%s\n",buff); } If I define a buffer of 10 elements and I'm trying to put inside it twelve elements, Should I receive a sigsev... (22 Replies)
Discussion started by: lagigliaivan
22 Replies

7. AIX

Segmentation fault

Hi , During execution a backup binary i get following error "Program error 11 (Segmentation fault), saving core file in '/usr/datatools" Riyaz (2 Replies)
Discussion started by: rshaikh
2 Replies

8. Programming

segmentation fault

ive written my code in C for implementation of a simple lexical analyser using singly linked list hence am making use of dynamic allocation,but when run in linux it gives a segmentation fault is it cause of the malloc function that ive made use of????any suggestions as to what i could do??? thank... (8 Replies)
Discussion started by: rockgal
8 Replies

9. Programming

Hi! segmentation fault

I have written a program which takes a directory as command line arguments and displays all the dir and files in it. I don't know why I have a problem with the /etc directory.It displays all the directories and files untill it reaches a sub directory called peers which is in /etc/ppp/peers.the... (4 Replies)
Discussion started by: vijlak
4 Replies

10. UNIX for Dummies Questions & Answers

Segmentation Fault

hello all, I tried a program on an array to intialise array elements from the standard input device.it is an integer array of 5 elements.but after entering the 4th element it throws a message called "Segmentation Fault" and returns to the command prompt without asking for the 5th element. ... (3 Replies)
Discussion started by: compbug
3 Replies
Login or Register to Ask a Question