Question:
segmentation fault in small c program?
amit_kumar8
2007-04-05 03:20:19 UTC
I wrote a small program in RHEL
the code is ..
#include

int main (int argc, char *argv){
//Parameter check
if (argc < 2){
printf("Incorrect number of input parameters.\nUsage %s file", argv[0]);
return EXIT_SUCCESS;
}

return EXIT_SUCCESS;
}


if I do not give any parameter to this code I get the following output

[amitk@express subscription]$ ./sub_csv
Incorrect number of input parameters.
Segmentation fault


I do not get any segmentation fault in case I do give it a parameter.

some one please help me how to get rid of this segmentation fault.
Five answers:
csanon
2007-04-05 03:24:32 UTC
The correct declaration for main is:

int main(int argc, char **argv) or int main(int argc, char* argv[]);
GCB-TO
2007-04-05 03:36:48 UTC
Your argv argument declaration should be char **argv or char *argv[] rather than char *argv. In other words:



int main (int argc, char **argv){

//Parameter check

if (argc < 2){

printf("Incorrect number of input parameters.\nUsage %s file", argv[0]);

return EXIT_SUCCESS;

}



return EXIT_SUCCESS;

}
vanoflen
2016-10-21 06:12:53 UTC
Segmentation fault implies you have performed some thing incorrect alongside with your memory administration. Are you utilising Linux (or comparable)? i think of you're, as you consult with it as a segmentation fault. if so, look at utilising Valgrind, which will spotlight which lines are inflicting unusual behaviour, in case you deliver jointly with -g in gcc, then execute your software with: $ valgrind ./programname It appears like your code could be super (as quickly as you have swapped the %s with %c) so i'm curious to be attentive to as to why this could take place. one element that's advisable to reveal screen out for is that 'length' as you have defined that's an int, while sizeof() returns a size_t (even however this could not matter), and in C (opposite to C++), you do no longer might desire to solid the return of malloc. the respond above on the subject of the nul-terminated string will reason issues because it writes previous the tip of para (4th index), and that's probably no longer needed as you're utilising it as an array, no longer a string.
lda
2007-04-05 18:46:57 UTC
Should be:

char **argv

or

char *argv[]
gobexe
2007-04-05 03:24:46 UTC
use char ** argv (instead of char *)


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...