Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a char pointer in C. Why considered dangerous? [duplicate]

Possible Duplicate:
What is the difference between char s[] and char *s in C?

I initialize a char pointer:

char *a="test";

I have read at some places that this is considered read-only and that it's dangerous.

Does that imply that the "test" is not allocated space in the heap? Does that mean that the string "test" can be written over later in the program?

---Expanding my question---

If I have initiliazed a as above and then I do a bunch of other initializations like:

int b=20;
char c[]="blahblahblah";

Can "test" in memory get overwritten with "20" or "blah"? Or does that scenario have no ground?

like image 561
Pithikos Avatar asked Jan 09 '12 21:01

Pithikos


2 Answers

This is dangerous because the string is not-modifiable. Attempting to do so results in undefined behavior.

So it's preferred to do:

const char *a = "test";

You are correct that "test" in this case is not allocated on the heap or the stack* and instead lies in static memory that is not-modifiable.

*The standard says nothing about the stack or heap, though that's how it's usually implemented.

On the other hand:

char a[] = "test";

Is safe to modify since it's just short-form for:

char a[] = {'t','e','s','t','\0'};

which is an ordinary modifiable array.

like image 115
Mysticial Avatar answered Oct 05 '22 07:10

Mysticial


A literal string in a C program is considered to be read-only and the compiler/linker/loader may arrange for the memory of that string to be in memory that is protected against writing.

Depending on your compiler and OS, the following may trigger a runtime error:

char *a = "test";
a[0] = 'T';

Of course, if you don't actually try to change the string data, then doing this is not dangerous per se. However, it's useful to get the compiler to assist you in ensuring this by declaring the pointer const:

const char *a = "test";

With this declaration, an attempt to a[0] = 'T' would be a compile error and would therefore be detected much sooner than runtime.

like image 21
Greg Hewgill Avatar answered Oct 05 '22 07:10

Greg Hewgill