Thursday, July 9, 2009

This C function is written to concatenate 2 strings?

This C function is written to concatenate 2 strings.


// How you can characterize this function ?


// Will it work ? Or not ?


// If this function has problems, can you fix them ?


// (keep in mind - this is a C function)





char* ConcatStrings(char* str1, char* str2)


{


char buf[1024];





strcpy(buf, str1);


strcpy(buf + strlen(str1), str2);


return buf;


}

This C function is written to concatenate 2 strings?
Well, I tried actually compiling the function and testing it with this:





int main(int argCount, char* argValues[])


{


char* s1 = "Hello ";


char* s2 = "there";





char* s3 = ConcatStrings(s1, s2);





printf("%s\n",s3);





system("PAUSE");


return 0;


}





And it seems to work. The only problem I can see is if str1 and str2 are together longer than 1024 characters. In that case, there would be a buffer overrun.





I see two ways to fix this. The first is just make sure there's going to be enough room in the character buffer:





if( (strlen(str1) + strlen(str2)) %26gt; 1024 )


{


printf("Error: unable to concatenate strings!");


return NULL;


}





Or, you could dynamically allocate the memory for the character buffer. Instead of the line char buf[1024] you could do:





char* buf = (char*)malloc( strlen(str1) + strlen(str2) );





Now there's no limit on how long the resulting string can be. However, whatever calls this function needs to free the memory itself. Like this:





char* s3 = ConcatStrings(s1, s2);


//do whatever with s3....


free(s3);





If that buffer isn't freed, there would be a memory leak.


No comments:

Post a Comment