我想了解当堆栈损坏时会发生什么。这是我试图理解的示例程序。我已经将缓冲区的大小定义为1个字节。但是在我输入第13个字节后堆栈损坏发生。为什么在第13个字节后会损坏?堆栈损坏使用缓冲区
C代码:
#include<stdio.h>
#include<string.h>
int main(int argc,char *argv[]){
char buffer[1];
strcpy(buffer,argv[1]);
printf("\n buffer : %s \n",buffer);
return 0;
}
汇编代码:
.file "buffer_overflow.c"
.section .rodata
.LC0:
.string "\n buffer : %s \n"
.text
.globl main
.type main, @function
main:
pushl %ebp
movl %esp, %ebp
andl $-16, %esp
subl $32, %esp
movl 12(%ebp), %eax
addl $4, %eax
movl (%eax), %eax
movl %eax, 4(%esp)
leal 31(%esp), %eax
movl %eax, (%esp)
call strcpy
movl $.LC0, %eax
leal 31(%esp), %edx
movl %edx, 4(%esp)
movl %eax, (%esp)
call printf
movl $0, %eax
leave
ret
.size main, .-main
.ident "GCC: (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5"
.section .note.GNU-stack,"",@progbits
如果你去写愚蠢的代码,然后期望愚蠢的结果。 –
@EdHeal - 我不认为OP会不同意。我怀疑他在试图理解为什么他在某些情况下崩溃,但在其他情况下不会。这使得这是关于缓冲区溢出性质的一个很好的问题。 – selbie
可能的重复[为什么我的程序崩溃时,我写过一个数组的末尾?](http://stackoverflow.com/questions/6452959/why-doesnt-my-program-crash-when-i- (请注意,该问题中的数组也被分配到堆栈中,以防您特别对堆栈(而不是堆)缓冲区溢出感兴趣)。 – jogojapan