Return a string declaration of a string using char *

First hello everyone, first post here.

Today I was wondering if this code is correct, it was written again by a friend for the microcontroller, and I have no chance to ask him.

The program works correctly, but I can't decide if it works by luck or not (don't believe in luck with programming). I don't even know if the title of this post is correct, sorry if it might be confusing. Code:

char  *textStatusErrorMessage( unsigned int codeStatus )
{
    switch ( codeStatus ) {

    case STATUS_1:
        return ( (char  *) " Status: 1 " );
        break;     
    case STATUS_2:
        return ( (char  *) " Status: 2 " );
        break;      
    default:
        sprintf( tmpBuf, " UNKNOWN STATUS   %03d ", codeStatus );
        return ( (char  *) tmpBuf ); //tmpBuf is global
        break;
    }
}

      

more precisely, this syntax is a bit obscure to me.

return ( (char  *) " Status: 1 " );

      

It returns char * of what? where is the "Status: 1" string stored? heaps / stack ???

Since it is implemented, the line is in the scope of the function, and I assume that after exiting the function with a return statement, I have no control over what is written in the pointer returned by the function itself.

From the way I see it, I would have a global array with various possible string parameters and return a pointer to the correct, selected CASE. Therefore, I know that the pointer I am returning is in a well-defined area of ​​memory.

So is this code wrong or not? What is the most correct solution?

Thanks DAN

+3


source to share


2 answers


In theory, this code is valid; string literals (for example " Status: 1 "

) have a type char[]

and lifetime equal to the lifetime of the entire program.

However, there are several problems:



  • In string literals, if anything tries to modify the returned string, undefined behavior occurs . Indeed, this function should return instead const char *

    .

  • It is not clear where it is declared tmpBuf

    , and if it does not indicate sufficient memory to store the data being written to it.

  • There is only one tmpBuf

    , so every time this function is called tmpBuf

    will be overwritten. This will likely lead to errors that make tracking difficult.

  • No drives needed.

+6


source


It returns char *

what?

Discards char[]

that a string literal has a value char*

. This is optional as it automatically converts to char*

.



where is the "Status: 1" string stored? heaps / stack ???

Typically, string literals are stored in the data (or parent) segment of the program. But it doesn't matter, what matters is that string literals have static storage duration, so the code is valid and the returned pointers do not point to local variables that do not exist after the function returns.

+3


source







All Articles