简体   繁体   中英

Segmentation fault at ./

I'm relatively new to C and I'm starting to work with threads and the command line; I just need help with a bit of debugging and error handling. I've run into a segmentation fault every time I try and process the code. It works fine if there is an argument for argv[1] . However, when trying to catch any errors, such as only entering "./example" and nothing else, it finds a segmentation fault.

I have tried variations of the following code to no avail, including looking to see if argc < 1 :

int main(int argc, char * argv[]){
   pthread_t worker1;
   int in;
   
   if(arv[1] == NULL){
      printf("ERROR HERE");
   }else{
      in = strtol(argv[1], &endptr, 10);
   }

   if(*endptr > in || *endptr == in){
      printf("please eneter a number larger than zero");
      return EXIT_FAILURE;
   }else{
      pthread_create(&worker1, NULL, worker, &in);
      pthread_join(worker1, NULL);
   }
   return EXIT_SUCCESS;
}

Below is the current code which I am using, I'm pretty sure it's something small that I'm overlooking. I have never used strtol before and was using atoi before, I have heard it's a better practice to do this. I'm relatively sure the error is in the code provided as when I test the thread function, it works fine; if more is needed please let me know!

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>

int main(int argc, char * argv[]){
   pthread_t worker1;
   int in = strtol(argv[1], &endptr, 10);

   if(*endptr > in || *endptr == in){
      printf("please eneter a number larger than zero");
      return EXIT_FAILURE;
   }else{
      pthread_create(&worker1, NULL, worker, &in);
      pthread_join(worker1, NULL);
   }
   return EXIT_SUCCESS;
}

You are trying to access an array without doing any kind of bounds checking first:

int main(int argc, char * argv[]){
   pthread_t worker1;
   int in = strtol(argv[1], &endptr, 10);
...

Who is to say that argv[1] exists? Certainly not your program, because it doesn't check that condition first. Add a check on argc to make sure you are getting the number of arguments you expect before trying to use them.

  if (argc > 1) {
    int in = strtol(argv[1], &endptr, 10);
  }

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