473,320 Members | 2,112 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Segfault in an if

The following code is causing a segfault at the first if statement.
Am I doing something wrong or is it a compiler bug?

//----------
#include <stdio.h>

int main(int argc, char *argv[])
{
int c;
FILE *inp;

if(argc > 2) {
printf("Too many arguments\n");
return 1;
} else if(argc > 1)
if((inp = fopen(argv[1], "r")) == NULL) {
printf("error: unable to open file %s\n", argv[1]);
return 2;
}
else
inp = stdin;
//..

--
mail to: randomzoo <at> spymac <dot> com
Nov 14 '05 #1
11 1645
H.A. Sujith vient de nous annoncer :
The following code is causing a segfault at the first if statement.
Am I doing something wrong or is it a compiler bug?

//----------
#include <stdio.h>

int main(int argc, char *argv[])
{
int c;
FILE *inp;

if(argc > 2) {
Do you mean here ?
printf("Too many arguments\n");
return 1;
} else if(argc > 1)
if((inp = fopen(argv[1], "r")) == NULL) {
printf("error: unable to open file %s\n", argv[1]);
return 2;
}
else
inp = stdin;
//..


Sounds good to me. Might be something else (try to rebuild all) or a
compiler's bug. Try with another one.
Nov 14 '05 #2
On Sat, 17 Jul 2004 10:16:33 -0700, H.A. Sujith wrote:
The following code is causing a segfault at the first if statement.
Am I doing something wrong or is it a compiler bug?

//----------
#include <stdio.h>

int main(int argc, char *argv[])
{
int c;
FILE *inp;

if(argc > 2) {
printf("Too many arguments\n");
return 1;
} else if(argc > 1)
if((inp = fopen(argv[1], "r")) == NULL) {
printf("error: unable to open file %s\n", argv[1]);
return 2;
}
else
inp = stdin;
//..


The following compiles and runs on my system (fedora core 2, gcc 3.3.3).
I would suspect that you have not found a compiler bug - printf is far
to common for behavior like this not to have been caught before.

int main(int argc, char** argv)
{
if(argc > 2)
{
printf("To many arguments\n");
return 1;
}
else
{
if(2 == argc)
{
printf("opening a file\n");
}
else
{
printf("redirecting stdin\n");
}
}

return 0;
}

Try doing a full recompilation, including manually removing any object
files, libraries and the like. If you still get an error, try running the
program under a debugger to see where you are actually seg-faulting.

Finally, as a side note, I use exit() to return from main not return. I
can not see this making any difference at all, but it is something that
you could try.

Hope this helps, if not try to provide more information - stack trace and
the like.

George
Nov 14 '05 #3
H.A. Sujith wrote:
The following code is causing a segfault at the first if statement.
Am I doing something wrong or is it a compiler bug?

//----------
#include <stdio.h>

int main(int argc, char *argv[])
{
int c;
FILE *inp;

if(argc > 2) {
printf("Too many arguments\n");
return 1;
} else if(argc > 1)
if((inp = fopen(argv[1], "r")) == NULL) {
printf("error: unable to open file %s\n", argv[1]);
return 2;
} HERE is the error!
this else behind is all about the if just above it.
not the else if, so when argc == 1, inp isnt initialized
the correction would be:
else if(argc > 1) {
if(...) {
}
}
else
inp = stdin; else
inp = stdin;
//..


--
Felipe Magno de Almeida
Ciencia da Computacao - Unicamp
fe************@ic.unicamp.br - UIN: 146989862
Cause Rock and Roll can never die.
"if you want to learn something really well, teach it to a computer."
What is Communism?
Answer: "Communism is the doctrine of the conditions of the liberation
of the proletariat." (by Karl Marx)
Nov 14 '05 #4
"H.A. Sujith" <su****@localhost.localdomain> wrote in message news:<slrncfidqt.dn9.su****@localhost.localdomain> ...
The following code is causing a segfault at the first if statement.
Am I doing something wrong or is it a compiler bug?

//----------
#include <stdio.h>

int main(int argc, char *argv[])
{
int c;
FILE *inp;

if(argc > 2) {
printf("Too many arguments\n");
return 1;
} else if(argc > 1)
if((inp = fopen(argv[1], "r")) == NULL) {
printf("error: unable to open file %s\n", argv[1]);
return 2;
}
else
inp = stdin;
//..


you sure it isn't the inp=stdin. That is not allowable you have to
close the file then fopen it again. I know it isn't the first or the
second one, both are correct.
Nov 14 '05 #5
>"H.A. Sujith" <su****@localhost.localdomain> wrote in message
news:<slrncfidqt.dn9.su****@localhost.localdomain >... [snippage]
... else if(argc > 1)
if((inp = fopen(argv[1], "r")) == NULL) {
printf("error: unable to open file %s\n", argv[1]);
return 2;
}
else
inp = stdin;


In article <20**************************@posting.google.com >
Michael <mi************@excite.com> writes:you sure it isn't the inp=stdin. That is not allowable you have to
close the file then fopen it again.


This claim is incorrect: "inp = stdin" is allowed, and sets the
"FILE *" object named "inp" to point to the same "FILE" object that
the name "stdin" refers to. (The "stdin" name is required to be
a macro, and might be defined as something like __stdin or &__sfiles[0]
or some such, but whatever the macro expands to must also have type
"FILE *" and point to a "FILE" object that ultimately refers to
the standard input.)

There is, however, an obvious bug in the code fragment remaining in
">>" above:

if (a)
if (b)
c();
else
d();

is improperly indented, and does not mean what it seems to suggest at
first glance. Fixing the indenting results in:

if (a)
if (b)
c();
else
d();

In other words, the "inp = stdin" assignment occurs only if argc > 1
*and* the fopen() call succeeds.

If the fopen() call does succeed, the reference to the underlying
FILE object is lost when "inp = stdin" overwrites the non-NULL "inp".
If argc <= 1, the variable "inp" remains uninitialized.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #6
George Huber <kh*****@optonline.net> wrote in message news:<pa****************************@optonline.net >...
On Sat, 17 Jul 2004 10:16:33 -0700, H.A. Sujith wrote:
<snip>

Finally, as a side note, I use exit() to return from main not return. I
can not see this making any difference at all, but it is something that
you could try.

You were doing fine until you said this. Please do not mislead the
youth. Quoth the standard:
5.1.2.2.3 Program termination

1. If the return type of the main function is a type compatible with
int, a return from the initial call to the main function is equivalent
to calling the exit function with the value returned by the main
function as its argument [...]
Mark F. Haigh
mf*****@sbcglobal.net
Nov 14 '05 #7
> HERE is the error!
this else behind is all about the if just above it.


eep

The lesson here is: Use emacs because it makes these problems obvious.
Nov 14 '05 #8
mf*****@sbcglobal.net (Mark F. Haigh) writes:
George Huber <kh*****@optonline.net> wrote in message
news:<pa****************************@optonline.net >...
On Sat, 17 Jul 2004 10:16:33 -0700, H.A. Sujith wrote:


<snip>

Finally, as a side note, I use exit() to return from main not return. I
can not see this making any difference at all, but it is something that
you could try.

You were doing fine until you said this. Please do not mislead the
youth. Quoth the standard:
5.1.2.2.3 Program termination

1. If the return type of the main function is a type compatible with
int, a return from the initial call to the main function is equivalent
to calling the exit function with the value returned by the main
function as its argument [...]


But I think the equivalence breaks down in some obscure circumstances
involving atexit().

--
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 14 '05 #9
In article <f8**************************@posting.google.com >,
Mark F. Haigh <mf*****@sbcglobal.net> wrote:
....
Finally, as a side note, I use exit() to return from main not return. I
can not see this making any difference at all, but it is something that
you could try.

You were doing fine until you said this. Please do not mislead the
youth. Quoth the standard:
5.1.2.2.3 Program termination

1. If the return type of the main function is a type compatible with
int, a return from the initial call to the main function is equivalent
to calling the exit function with the value returned by the main
function as its argument [...]


I'm sorry. Your point was?

If your point is: In a conforming implementation, there shouldn't be any
difference between them (and thus to imply that you shouldn't even consider
trying to solve your real world problem by trying one when you find that
the other doesn't do what you want), then, well, you're entitled, but you
might want to read the next paragraph.

Perhaps we need to make clear to all prospective posters here (by, at
a start, putting it in the FAQ) that helping people to solve their real
world problems is off-topic. Note: I am not saying for a second that there
is anything wrong with this stance - in fact, I rather like it, for
a variety of reasons, not least of which that it tends to keep the quality
level of the discussion high.

Nov 14 '05 #10
Kenny McCormack wrote:
In article <f8**************************@posting.google.com >,
Mark F. Haigh <mf*****@sbcglobal.net> wrote:
...
Finally, as a side note, I use exit() to return from main not return. I
can not see this making any difference at all, but it is something that
you could try.

You were doing fine until you said this. Please do not mislead the
youth. Quoth the standard:
5.1.2.2.3 Program termination

1. If the return type of the main function is a type compatible with
int, a return from the initial call to the main function is equivalent
to calling the exit function with the value returned by the main
function as its argument [...]

I'm sorry. Your point was?


I don't want any readers thinking that there's some kind of difference
between using exit and returning a value from main. People posting
answers here should take care to provide good advice, for the benefit of
less experienced readers. Changing the return to an exit is not good
advice in this context, and is not likely to solve or help solve any
problems.

If your point is: In a conforming implementation, there shouldn't be any
difference between them (and thus to imply that you shouldn't even consider
trying to solve your real world problem by trying one when you find that
the other doesn't do what you want), then, well, you're entitled, but you
might want to read the next paragraph.

Perhaps we need to make clear to all prospective posters here (by, at
a start, putting it in the FAQ) that helping people to solve their real
world problems is off-topic. Note: I am not saying for a second that there
is anything wrong with this stance - in fact, I rather like it, for
a variety of reasons, not least of which that it tends to keep the quality
level of the discussion high.


I think that's a bit heavy-handed. As you know, the consensus is that
people with problems post the smallest strict ANSI C fragment that can
reproduce the problem. If they can't post a problematic strict ANSI C
fragment, then they are generally redirected to the newsgroup for their
target platform.

Discussions of and questions about portable ANSI C code should not be
discouraged here. Rather, what should be discouraged (and actively is
my many regulars) is misleading or incorrect answers to these questions.
Mark F. Haigh
mf*****@sbcglobal.net
Nov 14 '05 #11
In article <cd**********@aracaju.ic.unicamp.br>, Felipe Magno de Almeida wrote:
H.A. Sujith wrote:
The following code is causing a segfault at the first if statement.
Am I doing something wrong or is it a compiler bug?

//----------
#include <stdio.h>

int main(int argc, char *argv[])
{
int c;
FILE *inp;

if(argc > 2) {
printf("Too many arguments\n");
return 1;
} else if(argc > 1)
if((inp = fopen(argv[1], "r")) == NULL) {
printf("error: unable to open file %s\n", argv[1]);
return 2;
}

HERE is the error!
this else behind is all about the if just above it.
not the else if, so when argc == 1, inp isnt initialized
the correction would be:
else if(argc > 1) {
if(...) {
}
}
else
inp = stdin;


Thats the problem! I forgot to put the braces.
(I'm kicking myself in the head with my leg right now, which is very
difficult BTW). But I still dont understand why my debugger(gdb 5.2)
said the problem was at line 8, the first 'if'. May be some compiler
(gcc 3.2) optimization I didn't consider.

Thanks for the help.
else
inp = stdin;
//..


--
mail to: randomzoo <at> spymac <dot> com
Nov 14 '05 #12

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

Similar topics

12
by: Nathaniel Echols | last post by:
I've written a function in C to perform protein sequence alignment. This works fine in a standalone C program. I've added the necessary packaging to use it in Python; it returns three strings and...
6
by: Juho Saarikko | last post by:
The program attached to this message makes the Python interpreter segfault randomly. I have tried both Python 2.2 which came with Debian Stable, and self-compiled Python 2.3.3 (newest I could find...
6
by: Stefan Behnel | last post by:
Hi! In Python 2.4b3, the deque is causing a segfault on two different machines I tested on. With deque, my program runs fine for a while (at least some tens of seconds up to minutes) and then...
0
by: dale | last post by:
Python newbie disclaimer on I am running an app with Tkinter screen in one thread and command-line input in another thread using raw_input(). First question - is this legal, should it run...
10
by: Arthur J. O'Dwyer | last post by:
I'm seeing a bug at the moment that I can't track down. It's part of a moderately large program, but here is a small program that exhibits the bug on gcc. (The program code follows at the bottom...
4
by: Jim Strathmeyer | last post by:
Under what circumstances would closing a istream object (such as 'in.close()') SEGFAULT?
4
by: William Payne | last post by:
Hello, I was under the impression that if I made a class Foo and if I didn't specify a copy constructor I would get one anyway that simply assigns the member variables (and that won't work for...
10
by: name | last post by:
When I started testing the algorithms for my wrap program, I threw together this snippet of code, which works quite well. Except that it (predictably) segfaults at the end when it tries to go...
3
by: kj | last post by:
I am trying to diagnose a bug in my code, but I can't understand what's going on. I've narrowed things down to this: I have a function, say foo, whose signature looks something like: int foo(...
14
by: Donn Ingle | last post by:
Yo, An app of mine relies on PIL. When PIL hits a certain problem font (for unknown reasons as of now) it tends to segfault and no amount of try/except will keep my wxPython app alive. My first...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.