Search code examples
cpointersc-stringscharacter-arrays

How do I return a variable size string from a function?


I need a working code for a function that will return a random string with a random length.

What I want to do would be better described by the following code.

char *getRandomString()
{
    char word[random-length];
    // ...instructions that will fill word with random characters.
    return word;
}
void main()
{
    char *string = getRandomString();
    printf("Random string is: %s\n", string);
}

For this, I am strictly forbidden to use any other include than stdio.h. Edit: This project will be adapted to be compiled for a PIC Microcontroller, hence I cannot use malloc() or such stuff. The reason why I use stdio.h here, is for me to be able to inspect the output using GCC.

Currently, this code gives this error.-
“warning: function returns address of local variable [enabled by default]”

Then, I thought this could work.-

char *getRandomString(char *string)
{
    char word[random-length];
    // ...instructions that will fill word with random characters.
    string = word;
    return string;
}
void main()
{
    char *string = getRandomString(string);
    printf("Random string is: %s\n", string);
}

But it only prints a bunch of nonsense characters.


Solution

  • There are three common ways to do this.

    1. Have the caller pass in a pointer to (the first element of) an array into which the data is to be stored, along with a length parameter. If the string to be returned is bigger than the passed-in length, it's an error; you need to decide how to deal with it. (You could truncate the result, or you could return a null pointer. Either way, the caller has to be able to deal with it.)

    2. Return a pointer to a newly allocated object, making it the caller's responsibility to call free when done. Probably return a null pointer if malloc() fails (this is always a possibility, and you should always check for it). Since malloc and free are declared in <stdlib.h> this doesn't meet your (artificial) requirements.

    3. Return a pointer to (the first element of) a static array. This avoids the error of returning a pointer to a locally allocated object, but it has its own drawbacks. It means that later calls will clobber the original result, and it imposes a fixed maximum size.

    None if these is an ideal solution.