January 18, 2006

Why does VC not generate a warning if a const-string in non-const parameters...

One of the questions in newsgroups/forms which come up over-and-over is: Why does the following code generates an access vialolation?:

CreateProcess(NULL, _T(“my.exe”), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);

And the answer is not very obvious… The second parameter of CreateProcess must be writable! And VC8 (7.1 also?) puts static (const) test literals into a read-only section. Therefor a write attempt to this string results in an access violation.

Now my qustion is: Why does the compiler not generate a warning if the “const” string is assigned to a non-const variable/paramater (LPTSTR)???

As a side effect of this: All examples in the MSDN are wrong if compiled with VC8!!!

CreateProcess

Creating Processes

Changing Environment Variables

Creating a Child Process with Redirected Input and Output

How to spawn console processes with redirected standard handles


Posted 1 year, 11 months ago on January 18, 2006
The trackback url for this post is http://blog.kalmbachnet.de/bblog/trackback.php/62/

Re: Why does VC not generate a warning if a const-string in non-const parameters...
Hi, I think you can find the question by searching for "const char* C++ string literals". You will find: http://groups.google.de/group/comp.lang.c++.moderated/browse_frm/thread/469c2984ec9c7e9b/4ffe4c3dd056b5e6?lnk=st&q=const+char*+C%2B%2B+string+literals&rnum=1&hl=de#4ffe4c3dd056b5e6 Extraction from this post: > char *w = "hello" ; // Incorrect, but still g++ allows this. All conforming compilers shall allow this although it breaks const correctness. This is a special exception applying to string literals which was added to avoid invalidating legacy code: it was considered too common that string literals are assigned to 'char*' variables or passed to functions taking this type as argument. New code should never do anything like this. Best Regards, Ulli
Posted 1 year, 11 months ago by Ullrich Praetz • • wwwReply
Comment Trackback URL : http://blog.kalmbachnet.de/bblog/trackback.php/62/356/
Re: Why does VC not generate a warning if a const-string in non-const parameters...
yea, it crushes in VC8, but in VC7 all is correct.
Posted 1 year, 11 months ago by Scherbina Vladimir • • wwwReply
Comment Trackback URL : http://blog.kalmbachnet.de/bblog/trackback.php/62/357/

Comments have now been turned off for this post