Gates Gates - 1 year ago 86
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

when I have run out of entries in
. 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
if(i < argc){

// Add else for odd numbered lists

return 0;

Answer Source

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"); }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download