views:

92

answers:

2

I have written a code that maps to a shared memory location,so that the first program opens a shared memory block and stores some data in it.And the second program reads the shared data.

Whats the difference between the two command lines:

1.

 if(argc<2)
 {
     printf("USAGE:%s text-to-share\n",argv[0]);
 }

This code gives me a Segmentation Fault if I run it without the second argument. However it works fine when I enter in some data.

2.

 if(argc<2)
    return printf("USAGE:%s text-to-share\n",argv[0]);

This one serves my purpose.

But I fail to understand the difference between the two. I'm a novice.For me the two are same,because ideally they should have the same output. Please Help!

+3  A: 

The two are obviously not the same:

printf("USAGE:%s text-to-share\n",argv[0]);        // From example 1
return printf("USAGE:%s text-to-share\n",argv[0]); // From example 2

The second line has something the first line does not: a return statement.

James McNellis
@James McNellis-Can you tell me what that 'something' is?
Pavitar
@James McNellis -But both of them,should do the same thing,right?(Correct me if I'm wrong.)
Pavitar
@Pavitar, no. Since you're not returning in the first one, the code will continue and still dereference `argv[1]`. Also, it's not really meaningful to return the result of `printf`; that's the number of characters outputted. Instead, return a fixed error code (e.g. 1).
Matthew Flaschen
@Pavitar: No. In the first example, the function continues executing after calling `printf`. In the second example, it returns to its caller and does not continue executing.
James McNellis
Thank you guys.@Matthew Flaschen- So what do you suggest?If I use (eg.1),how do I avoid the SegFault?
Pavitar
`main()` is supposed to return 0 on success and non-zero on failure. That convention is solidly established in *nix, and enshrined in the C standards as well. The only non-zero value that the standard requires your platform to allow is 1. For widest portability, return 1 (or call `exit(1)`) on failure. On *nix platforms in practice, you are allowed to return any value up to 127 so you can distinguish between kinds of failure.
RBerteig
+1  A: 

why first statment giving you segmentation fault,in C it name of the program which you are executing,so it should be absolutely fine.I am able to execute this testcase properly

int main(int argc,char ** argv){
    if(argc<2)
     {
         printf("USAGE:%s text-to-share\n",argv[0]);
     }
    return 0;
 }

it output :

USAGE:./prog text-to-share

except you are doing something wrong in the code executed before this.

Anil Vishnoi
@Anil Vishnoi-I wasn't returning 0.That was the problem. Thanks. +1
Pavitar
You shouldn't return 0 when there's an error (invalid parameters) because 0 indicates success; @Pavitar, you should return non-zero inside the if statement.
Matthew Flaschen