Gates Gates - 1 month ago 16
C Question

Basic Bool function giving segmentation fault

So I'm trying to learn functions a bit better and be able to write one that is useful and in then one that is recursive and sorts a list of number given to the program. However I'm getting a segmentation fault here. I feel this is occuring when I try to read

argv[i+1]
when I have run out of entries in
argv[]
. However why doesn't my
if(i < argc){
statement checking this preclude this from happening?

Here's my code.

#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <string.h>
#include <stdbool.h>

bool compare(val1,val2)
{
if(val1 > val2){return false;}
else{return true;}
}

// int values[], int n
int main(int argc, char *argv[])
{
for(int i=1; i<argc; i++){
//print unsorted list
printf("%s\n",argv[i]);
if(i < argc){
if(compare(*argv[i],*argv[i+1]))
{
printf("true\n");
}
else
{
printf("false\n");
}


}
// Add else for odd numbered lists
}

return 0;
}

Answer

argv[i+1] is not defined if i==argc-1.

For example, if argc=3 that means you are using 2 arguments (argv[0], argv[1] and argv[2] are defined). You are trying to access argv[3] when you call argv[i+1] when i is equal to 2.

All you have to do is to redefine you for and remove if(i < argc).

Your code may look like this :

for(int i=1; i < argc-1; i++){ //print unsorted list printf("%s\n",argv[i]); if(compare(*argv[i],*argv[i+1])) printf("true\n"); else printf("false\n"); }