Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

String Literals Have Proper Type of const char[]

String literals now have the type const char [] and are now placed in a read-only section of memory. Changing that memory will now cause an access violation. Code compiled in previous versions using /GF will also cause the access violation.

The following sample compiles and runs in Visual Studio .NET but will fail at run time in Visual Studio .NET 2003:

// bc_string_literals_have_proper_type_of_const_char.cpp
// compile with: /c
void f(char *c) {
   c[0] = 'Q';   // Now gives run-time access violation
}

int main() {
   f("TEST");
}

In addition, the run-time behavior of code such as the following example has now changed:

// bc_string_literals_have_proper_type_of_const_char2.cpp
#include "stdio.h"
void f(const char *) {   // called in Visual Studio .NET 2003
   printf_s("in f(const char *)\n");
}

void f(char *) {   // called in Visual Studio .NET
   printf_s("in f(char *)\n");
}

int main() {
   f("TEST");
}

To resolve this error, do not pass string literals to functions where they will be modified.

For code that will be valid in the current and previous versions of Visual C++ in the case where functions are overloaded in this manner:

  • Explicitly cast string literals to const char*.

  • Define variables on the stack or the heap.

The following code will be valid in the Visual Studio .NET 2003 and Visual Studio .NET versions of Visual C++, causing an access violation in neither:

// bc_string_literals_have_proper_type_of_const_char3.cpp
#include <stdio.h>
void f(const char *psz) {
   printf_s("const version\n");
}

void f(char *psz) {
   printf_s("version where we modify it\n");
   psz[0] = 'x';
}

int main() {
   char myStr[] = "TEST";
   f((const char*)"TEST");
   f(myStr);
}

Community Additions

ADD
Show:
© 2015 Microsoft