C++ cannot convert parameter 1 from 'const char *' to 'char *' -


i'm not c++ developer @ all, giving task of upgrading old code visual studio 6 visual studio 2010. i'm getting error following code.

messagegroup::messagegroup(const char *name, wordcollection *words) {     _name.assign(_strupr(name));     setwordcollection(words); } 

error:

error c2664: '_strupr' : cannot convert parameter 1 'const char *' 'char *' 

name constant c-style string. promises function's caller provided string not modified inside messagegroup constructor or functions called messagegroup.

_strupr(name) going convertname` upper case, violating no-modifications promise. bad thing do, possibly impossible memory region holding name may not writable, , generates error. perhaps in past generated warning , ignored. not on visual c 6 , it's default settings, or project settings should defaults have been changed silence warnings, i'm not sure if ever saw warning.

solutions problem are:

1. modify messagegroup remove const

messagegroup::messagegroup(char *name, wordcollection *words) 

this may break untold other pieces of code use messagegroup , count on name passing through unchanged. suggest because it's easy thing try. if blows up, put const , move on.

2. copy name new memory buffer writable.

char * temp = new char[strlen(name)];  _name.assign(_strupr(temp)); delete temp;  

but consider smart pointer instead because self-manages memory should bad things happen.

std::unique_ptr<char[]> temp(new char[strlen(name)]) _name.assign(_strupr(temp.get)); 

the nastiness here not know lifespan of name. responsible deleteing temp's memory when you're done it? if _name.assign copies pointer opposed making , keeping copy of data, messagegroup cannot clean-up because _name contain invalid pointer. if _name keeps copy, you're safe, have performance hit of copy.

modifications _name.assign , whatever class _name instantiates may required.

3. sizable rip-up

rewrite program modern techniques , std::string. error you've run across shows wasn't being careful memory use , there other time bombs waiting go off.

this out of scope stack overflow.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -