Groups | Blog | Home
all groups > visual c > december 2006 >

visual c : Access Violation error while using pointers


thejasviv
12/31/2006 12:38:00 PM
Dear All,

Here is my code:

void main()
{
char *p="Hello";
*p='M'; //This is where the error occurs
cout<<p<<endl;
}

This code compiles and executes perfectly in Boreland C++. When I run the
same code in VC++ 6.0, however, I get the below error in debugging mode:
Unhandled exception in Test.exe: 0xC0000005: Access Violation

Can someone please provide me a solution to this?

Thanks in advance,
David Wilkinson
12/31/2006 7:44:02 PM
[quoted text, click to view]

thejasviv:

When you write

char *p = "Hello";

you should really write

const char *p = "Hello";

because the string literal "Hello" is (or at least may be) in read-only
memory. Omitting the const is only permitted for legacy C reasons. If
you want to modify the string you should write

char p[] = "Hello";

David Wilkinson





thejasviv
1/1/2007 10:01:02 AM
Dear David/Ben,

Thank you so much for this reply. The answer was so explanatory. All my
doubts got cleared. Here is the new code snippet which works perfectly well:

void main()
{
char p[]={"Hellow"};
*p='M';
cout<<p<<endl;
getch();
}

Thanks,
thejasviv

[quoted text, click to view]
Ben Voigt
1/1/2007 10:45:50 AM

[quoted text, click to view]

Better, but still not correct. The compiler can still choose to use
read-only memory, because it's still a string literal.

Best is to use composite initializer syntax (an array is a composite):
char p[] = { "Hello" }; // identical to char[] p = { 'H', 'e', 'l', 'l',
'o', '\0' };

[quoted text, click to view]

Doug Harrison [MVP]
1/1/2007 5:57:49 PM
[quoted text, click to view]

But p is not a pointer; it's an array, and the compiler copies the string
literal into this non-const array. IOW, it's correct.

--
Doug Harrison
AddThis Social Bookmark Button