Reputation: 79
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <string.h>
#include <sys/types.h>
int main(int argc, char *argv[]){
int split;
pid_t childpid;
char *x = argv[1];
int status;
char splitindex_string[40];
split = atoi(x);
printf("%d\n" ,split );
int indexfile_split = 320000/split;
snprintf(splitindex_string,40, "%d", indexfile_split);
childpid = fork();
if(childpid==0){
execlp("/bin/split", "split", "l", splitindex_string, "-a", "1" ,"-d", "input.txt", "output", NULL);
return 0;
}
else{
int status;
wait(&status);
return 0;
}
}
i have this c code, but when i run the output i keep getting this weird segmentation fault (core dumped) error. the code compiles fine, the error only appears after i run the binary. from what I read online im probably accessing invalid memory. Ive been staring at this for hours now. help would be appreciated thanks
Upvotes: 0
Views: 780
Reputation: 50921
You need to check if your program is invoked correctly, for example like this:
int main(int argc, char *argv[]){
if (argc < 2)
{
printf("You didn't provide enough arguments\n");
return 1;
}
int split;
pid_t childpid;
...
If argc <2
then argv[1]
doesn't exist and dereferencing it will result in undefined behaviour.
Upvotes: 1
Reputation: 3535
The problem is the missed check over input. If you don't provide argument to the executable it crash, and give you the error you say.
I suggest you to introduce a check over the argument provided, before accessing them.
Upvotes: 1