Consider the following code:

#include<stdio.h>
#define SET_BIT(buf,n,val)buf[n]=val
int main()
{
char ch='D';
char *name="Yankee Duddle";
int i=5;
SET_BIT(name,i,ch);
printf("%s",name);
}

When compiling with Borland C it worked fine. However when I tried cimpiling it with VS 2005 I got the following error:
"Unhandled exception at 0x00413529 in Learning C.exe: 0xC0000005: Access violation writing location 0x00415645."

When I changed the code to:

char name[]="Yankee Duddle";

Instead of

char *name="Yankee Duddle";

It worked fine. I found this resolution in a forum.

But based on what I learnt in C I don't understand why it did not work in VS. And why by making it an array rather than a pointer it made a difference?

Recommended Answers

All 5 Replies

In case char *name="Yankee Duddle"; string literal turns into an unnamed, static array of characters, and this unnamed array may be stored in read-only memory, and which therefore cannot necessarily be modified. Trying to modify it is undefined behaviour.
Whereas in case of char name[]="Yankee Duddle"; you can modify the contents safely.

commented: Thanks for the explanation. +3

When compiling with Borland C it worked fine. However when I tried cimpiling it with VS 2005 I got the following error:
"Unhandled exception at 0x00413529 in Learning C.exe: 0xC0000005: Access violation writing location 0x00415645."

But based on what I learnt in C I don't understand why it did not work in VS. And why by making it an array rather than a pointer it made a difference?

char *name="Yankee Duddle"; is a constant, it can not be modified.
char name[]="Yankee Duddle"; the elements can be modified.
calling the SET_BIT in main you are trying to modify the value in char *name.

[EDIT]: Sorry, SPS your posted while I was writing this. Making this post a repetition.

Why do the two compilers behave differently?

> Why do the two compilers behave differently?
Because your code invokes undefined behaviour.
The assumption you made was that string constants can be modified, and they cannot.

If your code is correct, then you'll get the same answer with every compiler.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.