Returing a String in C

Hello, I am here to show you how to return a string from a C function.

Yes, really.

Honestly, I spent more time trying to figure this out than I would like to admit. On the bright side, I probably will not make this mistake again.

Let’s get straight into it!

The Failed Attempt

Here’s a simplified version of my initial attempt:

Looks fine, right? At least, it did to me.

Nope, I would get some obscure string with weird symbols (like 0║b%) after printing the result of this function. The best part was that the result was different every time the program ran.

Turns out the string I created in the function is destroyed once the function returns. Although I still receive a pointer to the address of the local variable, the variable does not exist anymore. As a result, the memory at the address is unpredictable.

My Solution

Variables declared in a function lives on the stack and are popped off once the function returns. To solve this problem, we need a way to keep the memory alive after the function ends.

The solution I used is as follows:

We add one additional byte in the malloc call to account for the null terminator. malloc allocates memory on the heap so the data persists after the function returns.

strcpy is used first because the variable is not initialized with a null terminator and strcat looks for the null terminator to begin concatenation.

One drawback of this method is that the caller of the function needs to deallocate the memory manually. This can be done by calling free on the returned pointer after processing is complete.

It is important to remember to free the memory to avoid memory leaks.

Closing Thoughts

I understand that there may be other methods of reaching the same solution. I know of at least one other approach where you can pass in an allocated string and manipulate it.

I chose this technique because I did not like the idea of out parameters. However, freeing memory manually outside the scope of the variable’s creation is not very clean as well. But like this section’s title states, this is my solution.

However, I am definitely open to hearing about more methodologies for returning strings in C and their benefits and/or drawbacks.

What is your preferred method of returning a string in C and why?

David Tran
 

David is a software developer with experience in web technologies and interest in software and hardware integration. He is a lifelong learner, an avid podcast listener, and an enthusiast of books of all genres.

Click Here to Leave a Comment Below 0 comments