简体   繁体   中英

String declaration segmentation fault

After declaring a string, I get a segmentation fault. I do not know how to address this error — can you explain?

Code version 1 (using typedef char *string; from cs50.h ):

int main (int argc, string argv[])
{
    string key = argv[1]; 
    checkKey(key, argc);
}

int checkKey(string text, int n)
{
    //check if text is alphabetical and if argc has the desired amount of command-line elements 
}

Code version 2:

#include <stdio.h>
#include <ctype.h>
#include <cs50.h>

int main (int argc, char* argv[])
{
    printf("%d elements in argc and %s in argv[1]\n", argc, argv[1]);
    char* key = argv[1];
}

If you run your program without command line arguments, it receives the value 1 for argc and an array argv of size 2 with the name of the program in argv[0] and NULL in argv[1] .

If your function charkKey() dereferences the pointer it receives as its first argument, you invoke undefined behavior, which can result in a segmentation fault.

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