ander_3035
ander_3035

Reputation: 39

Segmentation fault C

I've read about segmentation fault but I still with no idea why this simple code is giving me that error

#include <stdio.h>
#include <unistd.h>
#include <sysexits.h>
#include <stdlib.h>
#include <string.h>

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

        if( argc == 2 ){
            double i;
            char *finalPtr;
            double h = strtod(argv[2], &finalPtr);
            for(i=1;i<=h;i++){
                    printf( "\t%g\n", i);
            }
            return 0;
            exit( EX_OK );
       }
return 0;
}

I supose it's due to *finalPtr but I don't realize why. It seems I don't really understand the memory use in C...

Upvotes: 0

Views: 159

Answers (2)

PhilM
PhilM

Reputation: 11

offset by 0

Anytime, remeber this.

See it as mem , + 1 * argv is enough.

Upvotes: 0

Santosh A
Santosh A

Reputation: 5361

As you are verifying whether only for two command line arguments.

double h = strtod(argv[2], &finalPtr);

should be :

double h = strtod(argv[1], &finalPtr);

This is because: argc == 2 which implies number of command line arguments is 2 where
the first argument argv[0] will be the name of the executable/binary and the second argument argv[1] will be the command line arg passed by the user

Upvotes: 6

Related Questions