Return empty string in c

Viewed 5829

In my function I want to return an empty string "", function looks like this:

char *myFunction(nodeType *arg){
   if (something){
      return anotherFunction(arg);
   } else {
      return EMPTYSTRING;
   }
}

(EMPTYSTRING should be replaced with correct expression to return "")

Some ways I came up with:

return ""

return '\0'

What is the right way to return an empty string?

3 Answers

It is not good idea to return "". Because, it is const char and you may try to dealloc it in where you get it from the function and this likely crashes your application.

So, I would return strdup(""), so you can free it safely.

return '\0' is not correct; it is a null character.

return "";

is more correct.

And you can make a small test function to test returning an empty string, before your data structure is implemented.

\0 is indeed a null-pointer constant, not an empty string, so returning that would still return a null pointer.

However you've got another problem here.

If anotherFunction returns a string that you don't need to free() then it is correct to return "" here. If it returns a dynamically malloc()ated string that you must free(), then you also need to return a dynamically allocated empty string here - return calloc(1, 1); would do the trick.

Related