gpt4 book ai didi

c - 使用缓冲区的堆栈损坏

转载 作者:太空宇宙 更新时间:2023-11-04 07:28:50 26 4
gpt4 key购买 nike

我试图了解堆栈损坏时会发生什么。这是我试图理解的示例程序。我已将缓冲区的大小定义为 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

最佳答案

当 CPU 进入一个函数时,它需要将一些值压入内存堆栈。根据您的代码,在调用“strcpy”之前,堆栈帧在 x86 系统上显示如下。

------------  offset 13
char buffer[1]
------------ offset 12
char *argv[]
------------ offset 8
int argc
------------ offset 4
ret
------------ offset 0

所以在你写了13bytes之后,strcpy已经重写了ret区。当 main 完成时,它已损坏。

关于c - 使用缓冲区的堆栈损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15737166/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com