Different ways to pass strings out of functions in C

There are several different ways to pass strings out of functions in C. None of them are particularly pretty which is one of the reasons C has a steep learning curve.

The one thing you cannot do is create a string on the stack and then pass it out,

char *func(int n)
{
char mystring[10];
sprintf(mystring, "%d", n);
return mystring;
}

As soon as the function terminates the stack space is ‘freed’ so the next function will get it. Being a typical computer delete this means that the memory is not actually deleted so it might remain there long enough for your caller to actually use the memory, but only if they don’t call a function before using it.

The typical ways to do it are,

1) Allocate a string on the heap using malloc.

char *func(int n)
{
char *mystring;
mystring = (char*) malloc(10 * sizeof(char));
sprintf(mystring, "%d", n);
return mystring;
}

This is safe but the caller must remember to free the string.

2) Pass in the buffer to use.

void func(int n, char *buffer, size_t buff_len)
{
sprintf(mystring, "%d", n);
}

This tends to be the preferred solution. It allows the client to use whatever memory management strategy they want. It allows the function to concentrate on it’s functionality and not worry about memory allocation. The client could create the string on the stack or the heap, it’s no concern to the function.

Note that the function should check the buffer length passed in. This simple example doesn’t! It is quite common to allow some way to ask for the size of the buffer needed without actually writing to it.

3) Use a static buffer.

char *func(int n)
{
static char mystring[10];
sprintf(mystring, "%d", n);
return mystring;
}

This is simple to implement and might get the job done in some cases. Older library functions sometimes use this sort of approach. The problems arise when making subsequent calls to it while still having a pointer in play from the previous invocation. There are also general thread safety issues with this approach.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s