views:

357

answers:

4

I am expecting that both following vectors have the same representation in RAM:

char a_var[] = "XXX\x00";
char *p_var  = "XXX";

But strange, a call to a library function of type f(char argument[]) crushs the running application if I call it using f(p_var). But using f(a_var) is Ok!

Why?

+2  A: 

At a guess, the function f modifies the contents of the string passed to it.

Steve Jessop
yes, it modifies. but why f(p_var) makes crush and f(a_var) not?
psihodelia
because:char* p_var = "XXX";Can't be modified.
Pablo Santa Cruz
+15  A: 

The first creates an array of char containing the string. The contents of the array can be modified. The second creates a character pointer which points to a string literal. String literals cannot be modified.

anon
As I know, in ANSI C all can be modified
psihodelia
You know wrong. The standard forbids modifications of string literals.
anon
Ok, thanks! Now, I will remember it for ever :)
psihodelia
@psihodelia:Modifying a String literal invokes UB(Undefined Behaviour).
Prasoon Saurav
I don't have access to the C standard but the C++ standard states (2.13.4.2) "The effect of attempting to modify a string literal is undefined."
Andreas Brinck
@Andreas: The C standard says the same. Read section 6.4.5 :)
Prasoon Saurav
The first also performs an implicit copy operation, whereas the second doesn't. This is important on platforms that are memory constrained.
Thomas Matthews
@Thomas Not true, I'm afraid. The compiler will create the array contents at compile time,
anon
+9  A: 

Nice question.

It's answered on section 6 of the C-FAQ.

Pablo Santa Cruz
A: 

Arrays can be treated (generally) as pointers but that doesn't mean that they are always interchangeable. As the other said, your p_var points to a literal, something static that cannot be changed. It can point to something else (e.g. p_var = &a_var[0]) but you can't change the original value that you specified by quotes....

A similar problem is when you are define a variable as an array in one file, and then extern-use it as a pointer.

Regards

nikifor