I’m trying to strcat char *. However, I’ve noticed an issue.
struct d{
struct d* up //parent
char *path //path to d
char *name //path + breadth = name
}
for(j=0; j<b;j++){
struct d* breadth_p;
breadth_p=malloc(sizeof(struct d));
char buffer[256];
snprintf(buffer, sizeof(buffer), "/%d", j) //prepares buffer to have "/j"
breadth_p->up=cur_parent;
breath_path->path=cur_parent->up->name;
breadth_name=strcat(breadth->path, buffer);
printf("name: %s\n", breadth_p->name);
free(breadth_p);
}
so say I pass the cur_parent name and path as root and b as 3. the following prints out
root/0
root/0/1
root/0/1/2
I’m assuming that I didn’t free the breadth_p correctly so it’s concatenating the previous names.
the results I’m expecting is
root/0
root/1
root/2
Can anyone help me figure out why this is happening?
strcat()modifies in-place its first argument (appends the second argument to it) and then simply returns the modified input buffer. Read more about this behavior here.