0

I've been working on this code for hours but it always gives me error, I don't really know what to do. This code should return a string of 1s and 0s, reading a tree. I'll put in here both code and structures. When i try to execute it it gives me segmentation error, i don't know where's the problem. I want it to return 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;
}
paulsm4
  • 114,292
  • 17
  • 138
  • 190

1 Answers1

0

To expand on what @WeatherVane said in the comment, char *res = ""; allocates 1 byte (null character) to string res. When you concatenating into res, you're writing past the string bounds and eventually trashing memory that's outside of the array. At that point, behavior is undefined and could easily result in seg fault.

Kon
  • 4,023
  • 4
  • 24
  • 38
  • I modified like a 100 times but I just can't make it, there is always some kind of error.. I tried to modify it like this but it's wrong.. I just need to know how to make it without errors.. char res[]; if (cl[strlen(cl)-1]=="3"){ strcpy(res,cr); return res; }else{ strcpy(res,cl); return res; } – Hakim Maghraoui Oct 09 '18 at 21:24
  • I modified also the char* res="" to char res[] in the other function but nothing.. – Hakim Maghraoui Oct 09 '18 at 21:39