Question

#define MAXSTR "Maximum number reached"

char *str = MAXSTR;

While doing this kind of operation. Code is working & running fine but I am getting lint error. How I can resolve it?

Error:
Assignment of string literal to variable 

If I use:

 #define MAXSTR "Maximum number reached"

 char *str = (char *) MAXSTR;

then lint error:

Attempt to cast away const (or volatile)
Was it helpful?

Solution 2

Assignment of string literal to variable

That is a horrible error message. I'm curious about what Lint thinks string literals are good for, if we cannot assign them to variables... It should say something like: "assigning string literal to a non-constant pointer".

Attempt to cast away const (or volatile)

The warning is incorrect. Again, it should tell you that the pointer variable needs to be const.

To sum it up, you get those errors because your static analyser tool is bad.


Explanation:

String literals in C are character arrays, char []. They are unfortunately not treated as constant type const char[] by the language. This is a defect in the C language, because if you attempt a write access of a string literal, then it leads to undefined behaviour and the program might crash and burn. So you must treat string literals as if they were const arrays, even though they are not.

Therefore, it is good practice to always declare pointers to string literals as const char*.

In the case of Lint, it seems to treat string literals as if they were const char[], which they are not. Therefore it gives you incorrect errors instead of pointing out the actual problem.

OTHER TIPS

A macro is a name given to a fragment of code. Wherever the name occurs in the source file, it is replaced by the code fragment. Macro definitions are directives to the C preprocessor. They are not statements in the sense that they are not executed. They are not even there after the preprocessing stage and hence generate no assembly code.

MAXSTR is a macro which is replaced by the string literal "Maximum number reached". String literal are read-only and it's undefined behaviour to try to modify them. Therefore, you should make the pointer const qualified.

#define MAXSTR "Maximum number reached"

const char *str = MAXSTR;  // make the pointer const

you can copy the string, just make sure it has enough space:

#define MAXSTR "Maximum number reached"

char str[100];

strcpy(str, MAXSTR);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top