I have the following code where strcat is causing problem.
char* tokens = strtok(buf, "+");
int n = 0;
int type = 0;
char* name = "";
char* lifetime = "";
char* data = "";
for(n=0; tokens!=NULL; n++) {
if(n==0)
type = atoi(tokens);
if(n==1)
name = tokens;
if(n == 2) {
if(type == 1)
lifetime = tokens;
else
data = tokens;
}
if(n == 3)
lifetime = tokens;
tokens = strtok(NULL, "+");
}
if(type == 2) {
printf("Received Data with Name: %s, Data: \"%s\" and lifetime: %s seconds\n", name, data, lifetime);
strncat(name, "+", 1);
printf("Data: %s\n", data);
strncat(name, data, strlen(data));
printf("Full Name: %s\n", name);
}
In the line where I print the name, data and lifetime everything prints correctly. But after the strcat operations I find that data value is empty. After adding debug printf statements I have found that data value becomes empty right after strncat(name,"+",1). What could be the reason? Please help.
Both the name and data pointers point somewhere into the buf string. When concatenating into the name string, you probably happen to overwrite the data string with a null character. You need to allocate a new buffer for name before writing to it: