7

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?

6
  • 4
    '\0' is not correct. That's not a char *. You're returning null, not an empty string. Commented Oct 1, 2017 at 17:58
  • So is the "" same type as char* ? Commented Oct 1, 2017 at 17:58
  • 2
    I would've returned NULL in place of EMPTYSTRING Commented Oct 1, 2017 at 17:59
  • I can't return NULL, because later I concatenate returned values, so it will be worse implementation, if I have to check every returned values for NULL Commented Oct 1, 2017 at 18:00
  • 3
    If you don't return null, you're going to have to malloc every time you return an empty string because you're returning char * and not const char *. Just something to be aware of. return "" will give you read-only memory that shouldn't be freed. Commented Oct 1, 2017 at 18:02

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I would not assume anotherFunction allocated memory without seeing a code
@ArtemyVysotsky I assumed that anotherFunction allocates memory because the return type is char * and not const char *. Though I concede it's entirely possible they're just using the wrong return type. @OP, make sure to free the string returned from strdup.
3

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.

Comments

3

\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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.