c - 段错误(核心转储)错误 (C)

标签 c arrays string char segmentation-fault

我已经研究这个代码几个小时了,但它总是给我错误,我真的不知道该怎么做。这段代码应该返回一个由 1 和 0 组成的字符串,读取一棵树。我将在这里放置代码和结构。 当我尝试执行它时,它给我段错误,我不知道问题出在哪里。我希望它返回 char* 。

struct info{
    int frequency;
    char symbole;
}info;

typedef struct info* pinfo;

struct node{
    struct info* in;
    struct node* right;
    struct node* left;
}node;

typedef struct node* pnode;



struct tree{
    pnode root;
    int frequency;
};

typedef struct tree* ptree;

char * codage(char c, pnode pn){
    char cl[]=" ";
    char cr[]=" ";
    if(pn->in->symbole==c){
        return "";
    }else{
        printf("testtttK\n");
        if(pn->left==NULL){
            return "3";
        }else{
            strcpy(cl,strcat("1",codage(c,pn->left)));
            strcpy(cr,strcat("0",codage(c,pn->right)));
        }
    }
    char* res;
    if (cl[strlen(cl)-1]=="3"){
        res=cr;
        return res;
    }else{
        res=cl;
        return res;
   }
}

char* compress(char* txt, ptree pt){
   int i;
   char* res="";
   for(i=0;i<(int)strlen(txt);i++){
       res=strcat(res,codage(txt[i],pt->root));
   }
   return res;
}

最佳答案

为了扩展 @WeatherVane 在评论中所说的内容,char *res = ""; 为字符串 res 分配 1 个字节(空字符)。当您连接到 res 时,您的写入超出了字符串边界,并最终浪费了数组外部的内存。此时,行为是未定义的,很容易导致段错误。

关于c - 段错误(核心转储)错误 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52727444/

相关文章:

arrays - 找到数组中的最大数量并将字符串与它们关联

arrays - Autoit - 比较两个数组的每个元素

php mysql 从获取的数组行中删除编号键

java - 为什么 Integer.parseInt 在没有 try catch 的情况下进行编译?

C/XC8 语法 : Can invert and AND operation be used in the same statement?

c - 如何将数组传递给外部函数?

c - 如何在 Linux 设备上安装 clang?

php - 替换字符串或 explode() 函数

c - 将字符串分成更小的字符串

python - 亚里士多德数谜解说