18

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?

Josh Lee
  • 171,072
  • 38
  • 269
  • 275
psihodelia
  • 29,566
  • 35
  • 108
  • 157

4 Answers4

30

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.

1

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

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
1

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
  • 31
  • 3
1

As others said, char *p_var = "XXX"; creates a pointer to a string literal that can't be changed, so compiler implementations are free to reuse literals, for example:

char *p_var  = "XXX";
char *other  = "XXX";

A compiler could choose to optimize this by storing "XXX" only once in memory and making both pointers point to it, modifying their value could lead to unexpected behavior, so that's why you should not try to modify their contents.

Petruza
  • 11,744
  • 25
  • 84
  • 136