Tuesday 30 May 2017

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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...