Swanand
Swanand

Reputation: 4115

Returning pointer to static constant string via function

I have a file which has a static constant string and a function which will return pointer to that string. File looks like this:

typedef unsigned char   BOOLEAN;

#define TRUE    1
#define FALSE   0


static const unsigned char MAL_Version[8] = "2.001";

/* Function to return Version string */
BOOLEAN GetVersion ( unsigned char* pu8Version )
{
    BOOLEAN success = FALSE;

    if(pu8Version != NULL)
    {
        pu8Version = &MAL_Version[0];
        success = TRUE;
        printf("\r\nTRUE");
        printf("\r\n%s", pu8Version);
    }

    return success;
}

and in main(), I declare an array and pass it's address to GetVersion function. When I do this, I am getting random characters.

int main() {
   unsigned char buffer[10];

   GetVersion(buffer);
   printf("\r\n%s", buffer);
}

Output is:

TRUE

2.001

D�3�

What I am missing? The pointer in function is correctly printing the string, but when it returns, it prints garbage.

Upvotes: 1

Views: 566

Answers (3)

Bite Bytes
Bite Bytes

Reputation: 1513

Or you can pass a pointer to a pointer:

/* Function to return Version string */
BOOLEAN GetVersion ( unsigned char **pu8Version )
{
    BOOLEAN success = FALSE;

    if(*pu8Version != NULL)
    {
        *pu8Version = MAL_Version;
        success = TRUE;
        printf("\r\nTRUE");
        printf("\r\n%s", *pu8Version);
    }

    return success;
}

int main() {
   unsigned char *buffer;

   GetVersion(&buffer);
   printf("\r\n%s", buffer);
}

Upvotes: 0

P.P
P.P

Reputation: 121397

This statement

pu8Version = &MAL_Version[0];

only modifies the local pointer pu8Version in GetVersion() and that doesn't change buffer in main().

Instead of:

pu8Version = &MAL_Version[0];

you can copy the MAL_Version to buffer with:

strcpy(pu8Version, MAL_Version);

If you really don't need a copy of MAL_Version, you can also return the pointer to MAL_Version directly. Something like:

/* Function to return Version string */
const char *GetVersion(void)
{
    return MAL_Version;
}

int main(void) {
   const char *version = GetVersion();
   printf("\n%s", version);
}

Note that you don't define a "BOOLEAN" yourself. bool (from <stdbool.h> header) type is available in C since C99.

Upvotes: 5

Weather Vane
Weather Vane

Reputation: 34585

The function parameter pu8Version is the local copy of the pointer passed.

You change pu8Version to point to the static string MAL_Version which prints correctly. On returning fom the function, the changed version of pu8Version is forgotten.

The original unsigned char buffer[10]; is uninitialised and remains so, so rubbish is printed.

Note you cannot copy a C string with the = operator. What that does is to change the pointer, but not what it is pointing to. You should use strcpy.

Upvotes: 0

Related Questions