What are the issues with the following code in C?
char* copyStr(const char* someStr)
{
char buf[100];
sprintf(buf, “%s”, someStr);
return buf;
}
CodePudding user response:
There are 2 major problems in your code:
sprintf(buf, “%s”, someStr);
will attempt to store more than 100 bytes tobuf
if the string pointed to bysomStr
is longer than 99 bytes plus the null terminator, causing undefined behavior. This call is equivalent tostrcpy
with the same issue. You should always usesnprintf
instead ofsprintf
, passing the length of the destination array, thus preventing a buffer overflow.returning a pointer to a local array is incorrect as the object will go out of scope immediately upon exiting the function: the caller will invoke undefined behavior dereferencing this pointer.
For your purpose, you should allocate a block of memory, copy the string to it and return a pointer to it:
#include <stdlib.h>
#include <string.h>
char *copyStr(const char *someStr) {
size_t len = strlen(someStr);
char *p = malloc(len 1);
if (p != NULL) {
memcpy(p, someStr, len 1);
}
return p;
}
This is exactly the semantics of the function strdup
defined in POSIX and standardized the upcoming C23 Standard:
char *strdup(const char *s);