Monday, March 19, 2018

c - Under what circumstances (if ever) does strcat() hang?



I have this code in a function in C:



char* root = "/home/OS/homework/user/honorsupgrade/HTML";
requestInfo->resource = "/bing"
printf("1\n");
int counter = 0;
for(counter = 0; counter < 100; counter++)
{

if(root[counter] == '\0')
{
printf("True1\n");
break;
}
}
for(counter = 0; counter < 100; counter++)
{
if(requestInfo->resource[counter] == '\0')
{

printf("True2\n");
break;
}
}
printf("2\n");
fflush(stdout);
strcat(root, requestInfo->resource);
printf("3\n");
fflush(stdout);
return open(root, 0_RDONLY);



...



Request Info's stuff, as needed



struct ReqInfo
{
char *resource;
}



I have created two string (character pointers) in C, but for some reason when I pass these methods to strcat(), strcat() never returns. This causes the program to hang. I have tested to ensure that both strings have null terminators (so strcat isn't trying to concatenate more than it should). The program will print 1 and 2, but never print 3, meaning it never gets past the strcat() call, as I am flushing the buffer to make sure that there isn't a problem there. \



EDIT: I've created the struct outside of this block of code, I'm getting the same issues when replacing "requestInfo->resource" with a char* resource and making it "/bing"


Answer



Attempting to write to const char *



Even though char* root is a char *, it really points to a const char *. And writing to that is undefined behavior.




char* root = "/home/OS/homework/user/honorsupgrade/HTML";
....
strcat(root, requestInfo->resource);


Code should allocate a right sized working buffer instead.



char buffer[1000];
strcpy(buffer, root);
strcat(buffer, requestInfo->resource);


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...