Possible Duplicate:
Why does this Seg Fault?
Is the stack allocation is read only:
char* arr="abc";
arr[0]='c';
Can you change the string that is allocated on the sta开发者_StackOverflow中文版ck??
The string "abc"
isn't on the stack. A pointer to it (arr
) is. Modifying the string literal is undefined behaviour.
You can see this quite clearly in the asm GCC generates on x86:
.file "test.c"
.section .rodata
.LC0:
.string "abc" ; String literal inside .rodata section
.text
.globl main
.type main, @function
main:
pushl %ebp
movl %esp, %ebp
subl $16, %esp
movl $.LC0, -4(%ebp) ; Pointer to LC0 (our string onto stack)
movl -4(%ebp), %eax ; Pointer is copied into eax register
movb $99, (%eax) ; Copy $99 ('c') to what eax points to (in .rodata)
Your code doesn't allocate a string on the stack. It allocates a char*
on the stack, that is to say a pointer, and it makes that pointer point at a string literal. Attempting to modify the string literal is undefined behavior.
To allocate the string on the stack, do:
char arr[] = "abc";
Now you've taken a copy of the string literal in your stack-allocated array arr
, and you're allowed to modify that copy.
For full pedantry: everything I've described as "stack-allocated" are technically "automatic variables". C itself doesn't care where they're allocated, but I can guess with a lot of confidence that your implementation in fact does put them on a stack.
"abc"
is not allocated on the stack, it is a string literal.
No, you can't modify it. Your compiler can put that string in a read-only memory segment (if your implementation has such a concept). Trying to change it leads to undefined behavior.
(It crashes on Linux with GCC with default compile options for instance.)
精彩评论