代码之家  ›  专栏  ›  技术社区  ›  Jeffrey Hennen

segfault追加空字符串C

  •  -2
  • Jeffrey Hennen  · 技术社区  · 8 年前

    我正在尝试附加一个带有特定字符的字符串。我得到了一个segfault,我认为这是因为我试图附加到一个内存地址,我不知道我将如何改变这个。

    这是调试时显示的错误,

    打印:6

    附加字:ZHE

    分段故障(堆芯倾倒)

    这是对应于segfault的代码

    void append(char* s, char c){
    
            printf("print: 5\n");
            int len = strlen(s);
    
            printf("print: 6\n");
            printf("word to be appended: %s\n", s);
            s[len] = c;
    
            printf("print: 7\n");
            s[len+1] = '\0';
    }
    

    这是对上述函数的调用,位于这组代码的底部,带有相应的变量初始化

        int x;
        char *tempLine = NULL;
        char *token = NULL;
        char *punctuationChar;
        size_t length = 0;
        int charCount = 0;
        char *word;
        int i;
        int p;
        int check = 0;
        struct node *curr = NULL;
        struct node *newNode = NULL;
    
        (*head) = malloc(sizeof(struct node));   
        curr = (*head);     
    
        rewind(stream);
    
        for(x = 0; x < size; x++){
    
                getline(&tempLine, &length, stream);
                token = strtok(tempLine, " ");
                if(x == 0){
    
                        charCount = strlen(token);
                        curr -> word = malloc(charCount *(sizeof (char)) + 1);
                        strcpy(curr -> word, token);
                        token = strtok(NULL, " ");
    
                }else{   
    
                while(token != "\n"){
    
                        check = 0;
                        printf("token: %s\n", token);
                        charCount = strlen(token);
                        printf("print: 1\n");
    
                        //check for punctuation aka, last word on line
                        for(i = 0; i < charCount; i++){
                                printf("iteration: %d\n", x);
                                if(ispunct(token[i])){
    
                                        printf("print: 2\n");
                                        append(punctuationChar, token[i]);
                                        check = 1;
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   Stephan Lechner    8 年前

    你打电话 append(punctuationChar, token[i]) ,但punctionatChar尚未初始化。这会产生未定义的行为。

    为了克服这个问题,让我们 punctuationChar 指向正确分配的内存空间,该空间使用有效字符串初始化,即使用字符串终止字符初始化;

    要尝试,您可以简单地从以下几点开始:

    char tempBuffer[100] = "something to start with";
    char* punctationChar = tempBuffer;
    

    这不会解决程序流中可能出现的问题;但它应该显示出问题的根本原因。