Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

warning: deprecated conversion from string constant to 'char*'' [duplicate]

Possible Duplicate:
How to get rid of deprecated conversion from string constant to ‘char*’ warnings in GCC?

I use following function from library which i cannot change:

HRESULT DynamicTag(char * pDesc, int * const pTag ); 

I use it as follows. I have created the object of the class provided by the library that implements the above function.

int tag =0;
g_pCallback->DynamicTag("MyLogger", &tag);

I am getting following warning:

warning: deprecated conversion from string constant to 'char*'

What is the best way of getting rid of above warning? I don't want to allocate memory dynamically.

Info: I am using Vxworks6.8 compiler

like image 212
venkysmarty Avatar asked Sep 19 '11 08:09

venkysmarty


1 Answers

Dealing with unknown library

When passing literals and not other const string, and you are not sure if the library is modifiying the string, is easy to create a stack allocated temporary copy of the literal in C++ (inspired by How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC?):

char strMyLogger[]="MyLogger";
g_pCallback->DynamicTag(strMyLogger, &tag);

Use explicit cast to work around a weak library prototype

On most compilers explicit conversions avoid warnings, like:

 g_pCallback->DynamicTag(const_cast<char *>("MyLogger"), &tag);

Note: You can use this only when you are sure the function is really never modifying the string passed (i.e. when the function could be declared as const char *, but it is not, perhaps because the library writer has forgotten to add it). An attempt to modify a string literal is an undefined behaviour and on many platforms it results in a crash. If you are not sure, you need to make a writeable copy of the string, which may be dynamically allocated or even stack allocated, when you know some upper limit for the string size.

like image 140
Suma Avatar answered Oct 11 '22 14:10

Suma