Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with returning C strings

What is considered better practice when writing methods that return strings in C?

passing in a buffer and size:

void example_m_a(type_a a,char * buff,size_t buff_size)

or making and returning a string of proper size:

char * example_m_b(type_a a)

P.S. what do you think about returning the buffer ptr to allow assignment style and nested function calls i.e.

char * example_m_a(type_a a,char * buff,size_t buff_size)
{
...
return buff;
}
like image 211
Roman A. Taycher Avatar asked May 05 '11 05:05

Roman A. Taycher


People also ask

What does returning mean in C?

A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.

Can we return character in C?

Yes we can, but it will be technically unfeasible. Usually, main() is the entry point of a C program, and when the control reaches to the end of main(), the program terminates. Now, main() usually returns an integer, to give the status of execution(which is usually 0=success, 1=error1, 2=error2 and so on).

Which function returns a string within a string?

The function strstr returns the first occurrence of a string in another string. This means that strstr can be used to detect whether a string contains another string.

What does Strcat do in C?

The strcat() function concatenates the destination string and the source string, and the result is stored in the destination string.


2 Answers

Passing a buffer as an argument solves most the problems this type of code can run into.

If it returns a pointer to a buffer, then you need to decide how it is allocated and if the caller is responsible for freeing it. The function could return a static pointer that doesn't need to be freed, but then it isn't thread safe.

like image 126
Jonathan Wood Avatar answered Oct 08 '22 21:10

Jonathan Wood


Passing a buffer and a size is generally less error-prone, especially if the sizes of your strings are typically of a "reasonable" size. If you dynamically allocate memory and return a pointer, the caller is responsible for freeing the memory (and must remember to use the corresponding free function for the memory depending on how the function allocated it).

If you examine large C APIs such as Win32, you will find that virtually all functions that return strings use the first form where the caller passes a buffer and a size. Only in limited circumstances might you find the second form where the function allocates the return value (I can't think of any at the moment).

like image 29
Greg Hewgill Avatar answered Oct 08 '22 21:10

Greg Hewgill