Question

I am writing a school project in C and apparently something in this code is causing it to crash with SIGSEGV memory access violation error even though it compiles without any problems.

int P, H, S, R;
char *end;

if (argc != 5){
    printf("Incorrect ammount of parameters.\n");
    exit(1);
}

errno = 0;
P=strtod(argv[2],&end);
H=strtod(argv[3],&end);
S=strtod(argv[4],&end);
R=strtod(argv[5],&end);

if (errno != 0){
    printf("Wrong input: %s\n",strerror(errno));
    exit(1);
}

//I know have only integers in P,H,S,R, that's why I can afford to do the following. Please don't judge me.
if ((H < 0) || (S < 0) || (R < 0) || (H > 5000) || ( S > 5000) || ( R > 5000)){
    printf("Incorrect waiting time H,S,R >= 0 && H,S,R < 5001\n");
    exit(1);
}

if ((P < 1) || ((P % 2)==1)){
    printf("Must be even number bigger than 0.");
    exit(1);
}

Any ideas? EDIT: even if I put printf at the very beginning of the code i does not print anything, only memory access violation error which looks like this

Neoprávněný přístup do paměti (SIGSEGV) (core dumped [obraz paměti uložen])
Was it helpful?

Solution 2

The problem is here:

if (argc != 5)
…
R=strtod(argv[5],&end);

When argc == 5, argv[5] == NULL. You crash when you convert a null pointer. You should be using strtod() on argv[1] through argv[4]. It is unusual to use strtod() to convert strings to integers; usually, you'd use strtol() or one of its relatives.

OTHER TIPS

It would be best if you could track down the exact line where the error is occurring. You can do that in a debugger, or simply by putting printf statements all over the place and seeing what the last one that works is.

However, from a quick look, I think that the problem is here:

R=strtod(argv[5],&end);

SIGSEGV (segmentation fault) means that you attempted an invalid memory access. A few lines up, you checked that argc == 5. This means that the valid indices for argv are 0 through 4. There is no argv[5], and any attempt to read it results in undefined behaviour.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top