简体   繁体   中英

Pointers, passing arguments to main, and segfaults

The three things mentioned in the title are somewhat new to me. I am familiar with all of them conceptually but this is the first time I have tried to write my own program from scratch in C++ and it involves all three of these things. Here is the code:

int main(int argc, char *argv[])
{
FILE *dataFile;
char string [180];
dataFile = fopen(argv[1],"r");
fgets(string,180,dataFile);
fclose(dataFile);
}

It compiles fine, but when I execute using a simple input text file I get a segmentation fault. I have searched multiple tutorials and I can't figure out why. Any help would be appreciated.

There are two likely causes of a segmentation fault in your code:

  • argv[1] does not exist, in which case attempting to access it may result in a segfault. Check if (argc > 1) to avoid this problem.
  • fopen does not successfully open the file, in which case attempting to read from the file ( fgets ) or fclose it will cause a segmentation fault. Immediately after a call to fopen, you should check that the return value is not NULL , eg if (dataFile == NULL) .

There are a few things you should be checking here. It still may not do what you expect, but it will avoid the errors you're getting.

int main(int argc, char** argv)
{
  if(argc > 1) // FIRST make sure that there are arguments, otherwise no point continuing.
  { 
    FILE* dataFile = NULL; // Initialize your pointers as NULL.
    const unsigned int SIZE = 180; // Try and use constants for buffers. 
                                      Use this variable again later, and if 
                                      something changes - it's only in one place.
    char string[SIZE];
    dataFile = fopen(argv[1], "r");
    if(dataFile) // Make sure your file opened for reading.
    {
      fgets(string, SIZE, dataFile); // Process your file.
      fclose(dataFile); // Close your file.
    }
  }
}

Remember that after this, string may still be NULL. See 'fgets' for more information.

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