My struct looks like this:
struct tree{
char *name;
int num_subdirs;
struct tree **subdirs;
}
I am receiving a buffer that contains this entire tree serialized in a buffer. I am trying to deserialize it in this function:
struct tree *t;
//buffer is filled, received from somewhere else.
int res = deserialize(t, buf); //call function deserialize
//deserialize function
//buf = {../,2}{sd,0}{|}{sr,1}{sk,0}{|}{|}
│406 int dfsDeserialize(struct tree *dt, void *buf, int *q){ │
│407 char name[MAXPATHLEN]; │
│408 char delim[3]; │
│409 int len, numsubs, i; │
│
│411 sscanf(buf+(*q),"%3s",delim); │
│412 if(!strcmp(delim,"{|}")){ │
│413 (*q)+=3; │
│414 return 1; │
│415 } │
│416 sscanf((buf + (*q)), "{%[^,],%d}%n", name, &numsubs, &len); │ │
>│419 int slen = strlen(name); │
│420 dt->name = calloc(slen + 1, 1); │
│421 dt->subdirs = malloc(numsubs*sizeof(struct tree *)); │
│422 strcpy(dt->name, name); │
│423 dt->num_subdirs = numsubs; │
│424 (*q)+=len; │
│425 for(i = 0; i< numsubs; i++){ │
│426 dt->subdirs[i] = malloc(sizeof(struct tree)); │
│427 dfsDeserialize(dt->subdirs[i], buf, q); │
│428 } │
│429 return 0; │
│430 }
│
I have tried several different ways of allocating memory for string but it fails every single time! I don't know why is t->name always 0x0. Please help.
tto the functiondfsDeserialize?valgrind? If so, use it. If not, life is harder.tis like a local variable and what it points to after you leave the function will be lost. if you want to permanently change whattpoints to you need to pass the address oft%3sbut the array is only 3 bytes long. Unfortunately, thescanf()functions take the size excluding the null terminator, so you have a one-byte overwrite potential, which can be disastrous. Increase the size ofdelimto at least 4, or change the format to specify 2 instead of 3. Whether that's the cause of all your trouble is open to debate, but buffer overflows are never good news.