I've been C# developer.
But Now I have to write C code.
I used to use String.IsNullOrEmpty()
for preventing Errors and assign a new string.
I hope to write C code to act like String.IsNullOrEmpty. and assign a new string
so I wrote some sample code.
static char *pCtvUrl;
void set_app_url(const char* appUrl){
if(!appUrl || !*appUrl)
return;
pCtvUrl = malloc(sizeof(appUrl));
strcpy(pCtvUrl,appUrl);
}
I want to check if this is correct or not.
If you know better way to solve, please give me some advice.
thanks
Your check for a NULL or empty string is correct
Change:
pCtvUrl = malloc(sizeof(appUrl)); /* This would allocate sizeof(char*) only. */
to:
pCtvUrl = malloc(sizeof(char) * (strlen(appUrl) + 1)); /* '+1' is for null terminator.*/
You also need to free()
memory of pCtvUrl
before reassigning it:
static char *pCtvUrl = 0;
Before pCtvUrl = malloc(...);
call free(pCtvUrl);
.
Instead of using a global variable consider changing set_app_url()
to return a copy of the string:
char* set_app_url(const char* appUrl)
{
char* retVal = 0;
if (appUrl && *appUrl)
{
retVal = malloc(strlen(appUrl) + 1);
strcpy(retVal,appUrl);
}
return retVal;
}
The caller would be responsible for freeing the returned string.
Checking whether appUrl
is NULL
or "empty" is correct.
However, calling your set_app_url
function more than once will lead to memory leaks. You don't free previous pCtvUrl
.
Also, you may have buffor underrun. You need to malloc strlen(appUrl) + 1
. Anyway, I suggest strdup
to use here, instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.