C堆栈分配

Vla*_*adp 1 c stack memory-management

可能重复:
为什么这个Seg Fault?

堆栈分配是只读的:

char* arr="abc";
arr[0]='c';
Run Code Online (Sandbox Code Playgroud)

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

Fle*_*exo 7

字符串"abc"不在堆栈中.指向它(arr)的指针是.修改字符串文字是未定义的行为.

您可以在asm GCC上生成的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)
Run Code Online (Sandbox Code Playgroud)


Ste*_*sop 5

您的代码不会在堆栈上分配字符串.它char*在堆栈上分配一个,也就是说一个指针,它使该指针指向一个字符串文字.尝试修改字符串文字是未定义的行为.

要在堆栈上分配字符串,请执行以下操作:

char arr[] = "abc";
Run Code Online (Sandbox Code Playgroud)

现在,您已经在堆栈分配的数组中获取了字符串文字的副本arr,并且您可以修改该副本.

对于完整的迂腐:我所描述的所有"堆栈分配"在技术上都是"自动变量".C本身并不关心它们的分配位置,但我可以非常自信地猜测你的实现确实会将它们放在堆栈中.