472,980 Members | 2,068 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,980 software developers and data experts.

Beginner requesting help - Segmentation fault

Hi everybody,
I'm trying to make the following code running properly, but I can't get
rid of the "SEGMENTATION FAULT" error message when executing.
Reading some messages posted earlier, I understood that a segmentation
fault can occur whenever I declare a pointer and I leave it
un-initialized.
So I thought the problem here is with the (const char *)s in the stuct
flightData (please note that I get the same fault declaring as char *
the members of struct flightData), but I can't figure out why.
Please also note that I've declared struct flightData members as char *
instead of char vectors, because I can't assume a value for the maximum
lenght of town names in flights.dat.

Could someone kindly explain the reason for I get the segmentation
fault, and suggest a way to make the program run properly?

Many thanks
Fra

The source code was compiled with GCC 3.3.5 (both with and without
-ansi option: the result is always the same) under Linux Knoppix 3.7
Live (kernel 2.6.9)

*** Here is the content of flights.dat:

Madrid Roma AA
Paris London UA
Milano Roma AZ
Milano New_York AZ
Berlin Milano LA
Roma Paris AZ
*** Here is the source code of fly3.c:

#include <stdio.h>
#include <string.h>

#define DEBUG

struct flightData {
const char * takeoffTown;
const char * landingTown;
const char * code;
};

/* ...omitted function prototypes... */

int main( int argc, const char *argv[] )
{
struct flightData flight;
FILE *flightsFPtr, *takeoffsFPtr, *landingsFPtr, *companiesFPtr;

if ( argc != 3 ) {
printf( "Usage: fly3 flights.dat Town - Aborting program fly3\n"
);
return 0;
}
if ( (flightsFPtr = fopen( argv[1], "r" )) == NULL ) {
printf( "Cannot open file %s - Aborting program fly3\n" );
return 0;
}

#ifdef DEBUG
printf( "Opening output files...\n" );
#endif
takeoffsFPtr = fopen( "takeoffs.dat", "w" );
landingsFPtr = fopen( "landings.dat", "w" );
companiesFPtr = fopen( "companies.dat", "w" );

#ifdef DEBUG
printf( "Scanning file %s...\n", argv[1] );
#endif
while ( !feof(flightsFPtr) ) {
#ifdef DEBUG
printf( "Reading %s...\n", argv[1] );
#endif
fscanf( flightsFPtr, "%s%s%s", &flight.takeoffTown,
&flight.takeoffTown, &flight.code );

#ifdef DEBUG
/* NEXT THREE LINES ARE FOR DEBUGGING PURPOSES */
printf( "I've read file %s...\n", argv[1] );
printf( "Town entered by user: %s\n", argv[2] );
printf( "I've read takeoff from: %s\n", flight.takeoffTown );
/* HERE I GET SEGMENTATION FAULT IF DEBUGGING*/
#endif

/* testing if the town name entered by user matches the name
stored in flight.takeoffTown */
if ( strcmp(flight.takeoffTown, argv[2]) == 0 ) { /* HERE I GET
SEGMENTATION FAULT IF NOT DEBUGGING */
#ifdef DEBUG /* COULDN'T EVER EXECUTE FROM THIS LINE ON... =(
*/
printf( "Writing on takeoffs file...\n" );
#endif
writeData( takeoffsFPtr, flight );
if ( stringPresence( companiesFPtr, flight.code ) == 0 ) {
#ifdef DEBUG
printf( "Writing on companies file...\n" );
#endif
fprintf( companiesFPtr, "%s\n", flight.code );
}

/* *** ...omitted the remaining code... *** */
*** and finally the output running the executable:

$ fly3 flights.dat Milano
Opening output files...
Scanning file flights.dat...
Reading flights.dat...
I've read file flights.dat...
Town entered by user: Milano
Segmentation fault
$

Nov 15 '05 #1
5 2924
You didn't allocation space for takeoffTown, landingTown, and code
before using them.

struct flightData {
const char * takeoffTown;
const char * landingTown;
const char * code;
};

Nov 15 '05 #2
"Fra-it" <fr***************@yahoo.it> writes:
[...]
struct flightData {
const char * takeoffTown;
const char * landingTown;
const char * code;
};
Since you want to initialize the strings these members point to, why
did you declare them as const?

[...] fscanf( flightsFPtr, "%s%s%s", &flight.takeoffTown,
&flight.takeoffTown, &flight.code );


The "%s" fscanf format expects a char*. You're passing a char** (the
address of a (const) char* object). This invokes undefined behavior;
the most likely consequence is that the string overwrites the pointer
and (if it's longer than sizeof(char*) bytes) some of the memory
following it.

You need to pass a char* to fscanf(), *and* you need to allocate
enough space to hold the input string. You can specify a maximum
field width to limit the size of the input.

Also, you probably didn't want to specify flight.takeoffTown twice.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #3
Keith Thompson wrote:
Which is exactly what he said he did. Either he didn't do what he
said (presumably an honest mistake), or he used the proper "Reply"
button and then deleted the quoted text and attribution. (Or Google
is now even more broken than it was before.)


Yes, I clicked "Show options", then "Reply" and deleted all the quoted
text...
indeed mine was simply a general thanks to all people who gave me their
suggestions.
By the way, thanks to you all I'm rearranging the code of fly3.c this
weekend, learning something about malloc() and beginning to learn to
use a compiler...
Greets
Fra-it

Nov 15 '05 #4
Fra-it wrote:
Keith Thompson wrote:
Which is exactly what he said he did. Either he didn't do what he
said (presumably an honest mistake), or he used the proper "Reply"
button and then deleted the quoted text and attribution.


Yes, I clicked "Show options", then "Reply" and deleted all the
quoted text...


Looks like you need to expand your advice block a bit, Keith :)

Nov 15 '05 #5
"Old Wolf" <ol*****@inspire.net.nz> writes:
Fra-it wrote:
Keith Thompson wrote:
Which is exactly what he said he did. Either he didn't do what he
said (presumably an honest mistake), or he used the proper "Reply"
button and then deleted the quoted text and attribution.


Yes, I clicked "Show options", then "Reply" and deleted all the
quoted text...


Looks like you need to expand your advice block a bit, Keith :)


No, I think this was an unusual case. The followup in question was a
general reply to everyone who had replied; there probably wasn't any
context in the immediate parent article that was necessary for
Fra-it's followup to be understandable. It was a problem only because
it *looked* like the usual context-free Google followup.

(It's not clear that a general "thanks, everyone" followup is really
necessary, but I won't get into that.)

If you're going to post a followup that really doesn't depend on the
parent article, it's probably a good idea to include some context
anyway, at least an attribution line and a "[snip]" -- not because
it's really necessary, but because it avoids confusion.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: sivignon | last post by:
Hi, I'm writing a php script which deals with 3 ORACLE databases. This script is launch by a script shell on an linux machine like this : /../php/bin/php ./MySript.php (PHP 4.3.3) My script...
3
by: diyanat | last post by:
i am writing a cgi script in C using the CGIC library, the script fails to run, i am using apache on linux error report from apache : internal server error Premature end of script headers:...
16
by: laberth | last post by:
I've got a segmentation fault on a calloc and I don'tunderstand why? Here is what I use : typedef struct noeud { int val; struct noeud *fgauche; struct noeud *fdroit; } *arbre; //for those...
3
by: Zheng Da | last post by:
Program received signal SIGSEGV, Segmentation fault. 0x40093343 in _int_malloc () from /lib/tls/libc.so.6 (gdb) bt #0 0x40093343 in _int_malloc () from /lib/tls/libc.so.6 #1 0x40094c54 in malloc...
18
by: Digital Puer | last post by:
Hi, I'm coming over from Java to C++, so please bear with me. In C++, is there a way for me to use exceptions to catch segmentation faults (e.g. when I access a location off the end of an array)?...
27
by: Paminu | last post by:
I have a wierd problem. In my main function I print "test" as the first thing. But if I run the call to node_alloc AFTER the printf call I get a segmentation fault and test is not printed! ...
7
by: pycraze | last post by:
I would like to ask a question. How do one handle the exception due to Segmentation fault due to Python ? Our bit operations and arithmetic manipulations are written in C and to some of our...
3
by: madunix | last post by:
My Server is suffering bad lag (High Utlization) I am running on that server Oracle10g with apache_1.3.35/ php-4.4.2 Web visitors retrieve data from the web by php calls through oci cobnnection...
6
by: DanielJohnson | last post by:
int main() { printf("\n Hello World"); main; return 0; } This program terminate just after one loop while the second program goes on infinitely untill segmentation fault (core dumped) on...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
4
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.