简体   繁体   中英

Generate function using /dev/random showing Segmentation fault (core dumped) error when called

The following code is supposed to be run from terminal so you should be able to choose different functions by just typing the name of a function and providing it with arguments (for example ./program generate dog 5 20 should generate 5 lines each with 20 characters and save them into the the file called dog). The other functions that you can see here may be a part of a problem that's why I'm including them although the problem itself occurs when I try to generate things. As you can see other functions are just declarations now mostly cuz I wanted to test if the first one was working correctly before going to others.

I was thinking that maybe I should write something that would actually take data from console input and put them directly into what's called "a" and "b" but if there is a problem with the function itself it won't help at all.

#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>



void generate(const char *str, int a, int b);

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

    int if_generate = (strcmp("generate", argv[1])==0);
    
    
    if (if_generate){
    generate(argv[2], argv[3], argv[4]);
}else{
printf("wrong function name");
}


}

void generate(const char *str, int a, int b){

    int n,m;
    int myFile = open(str, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR |S_IWUSR);
    int randomiser = open("/dev/urandom", O_RDONLY);
    char bufor[b+1];
    for(n=0; n<a; n++){
    for (m=0; m<b; m++){
        read (randomiser, &bufor, 1);
        write (myFile, &bufor, 1);
    }
        write(myFile, "\n", 1);
    }
    
}
    

    

Using information provided by @Barmar and @WeatherVane i changed the code a bit and it worked as intended.


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

    int if_generate = argc>=5 && strcmp("generate", argv[1])==0;
    
    
    if (if_generate){
    int x,y;
    x=atoi(argv[3]);
    y=atoi(argv[4]);
    generate(argv[2], x, y);
}else{
printf("wrong function name");
}


}

that was all that was required for this to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM