Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

c - String literals: pointer vs. char array

In this statement:

char *a = "string1"

What exactly is string literal? Is it string1? Because this thread What is the type of string literals in C and C++? says something different.

Up to my knowledge

int main()
{
    char *a = "string1"; //is a string- literals allocated memory in read-only section.
    char b[] = "string2"; //is a array char where memory will be allocated in stack.

    a[0] = 'X'; //Not allowed. It is an undefined Behaviour. For me, it Seg Faults. 
    b[0] = 'Y'; //Valid. 

    return 0;
} 

Please add some details other than above mentioned points. Thanks.

Debug Output Showing error in a[0] = 'Y';

Reading symbols from /home/jay/Desktop/MI/chararr/a.out...done.
(gdb) b main
Breakpoint 1 at 0x40056c: file ddd.c, line 4.
(gdb) r
Starting program: /home/jay/Desktop/MI/chararr/a.out 

Breakpoint 1, main () at ddd.c:4
4   {
(gdb) n
6   char *a = "string1";
(gdb) n
7   char b[] = "string2";
(gdb) 
9   a[0] = 'Y';
(gdb) 

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400595 in main () at ddd.c:9
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can look at string literal as "a sequence of characters surrounded by double quotes". This string is stored at read-only memory and trying to modify this memory leads to undefined behavior.

So how come that you get segmentation fault?
- The main point is that char *ptr = "string literal" makes ptr to point to the read-only memory where your string literal is stored. So when you try to access this memory: ptr[0] = 'X' (which is by the way equivalent to *(ptr + 0) = 'X'), it is a memory access violation.

On the other hand: char b[] = "string2"; allocates memory and copies string "string2" into it, thus modifying it is valid. This memory is freed when b goes out of scope.

Have a look at Literal string initializer for a character array


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...