c - 段错误追加空字符串 C

标签 c string algorithm segmentation-fault append

我正在尝试 append 一个带有特定字符的字符串。我认为出现了段错误,因为我正在尝试 append 到内存地址,但我不知道如何更改它。

这是我调试时显示的错误,

print: 6

word to be appended: ����Z�����H���E

Segmentation fault (core dumped)

这是段错误对应的代码

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;

最佳答案

您调用append(punctuationChar, token[i]),但 punctionatChar 尚未初始化。这会产生未定义的行为。

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

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

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

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

关于c - 段错误追加空字符串 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49870895/

相关文章:

c++ - 为什么这个结构是用字段中已有的数据初始化的?

mysql - MySQL中最右边出现的字符串匹配

c++ - 是否有好的数据翻译/转换模式/习惯用法?

java - 搜索二叉搜索树 (BST) 的最佳算法

c - 为什么我在测试中得到 '0' 作为返回值?

用 c 中的数组构造我自己的 strcat 函数

c - 测试用例未在 C 程序中运行

java - String.substring 在 Java 中究竟做了什么?

java - 字符串的正则表达式包含不在特定集合中的字符

计数交替向上/向下序列