c - C堆栈分配

扫码查看

Possible Duplicate:
Why does this Seg Fault?
堆栈分配是否为只读:

char* arr="abc";
arr[0]='c';

你能改变在堆栈上分配的字符串吗??

最佳答案

字符串"abc"不在堆栈上指向它的指针(arr)是修改字符串文本是未定义的行为。
您可以在x86上生成的asm GCC中清楚地看到这一点:

        .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)

关于c - C堆栈分配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7659483/

10-11 22:36
查看更多