gpt4 book ai didi

c - Strcat 堆栈粉碎行为

转载 作者:行者123 更新时间:2023-12-02 04:54:28 25 4
gpt4 key购买 nike

当运行以下故意堆栈粉碎代码时,strcat 将 source 的值复制十次。

#include <stdio.h>
#include <stdlib.h>

int main() {
char a[16];
char b[16];
char c[32];

strcpy(a, "abcdefghijklmnop");
printf("a = %s\nb = %s\nc = %s\n\n", a, b, c);

strcpy(b, "ABCDEFGHIJKLMNOP");
printf("a = %s\nb = %s\nc = %s\n\n", a, b, c);

strcpy(c, b);
printf("a = %s\nb = %s\nc = %s\n\n", a, b, c);

strcat(c, b);
printf("a = %s\nb = %s\nc = %s\n\n", a, b, c);

return 0;
}

输出:

a = abcdefghijklmnop b = c =

a = abcdefghijklmnopABCDEFGHIJKLMNOP b = ABCDEFGHIJKLMNOP c =

a = abcdefghijklmnopABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP b = ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP c = ABCDEFGHIJKLMNOP

a = abcdefghijklmnopABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP b = ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP c = ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP

** stack smashing detected *: ./strcpytest terminated

构建参数:

gcc -O0 -g3 -Wall -c -fmessage-length=0

代码在 x86_64 架构上运行。

为什么只连接十次?

最佳答案

对于重叠字符串,strcpy() 和 strcat() 的行为未定义。因此,您对 c[] 的两次写入都是可疑的,您不仅仅是测试破坏堆栈,还测试编译器对这种未定义行为的处理。

我预计 strcpy(c, b) 行会失败,但实现必须以某种方式获取 b 的长度,然后才能覆盖 c 开头的尾随零。例如,如果它从最后一个字节复制到第一个字节,则可能会发生这种情况。

strcat(c, b) 可以以更直接的方式实现。也许十倍的数据足以达到终止它的某个限制。

如果您只想测试是否损坏堆栈,请不要使用这些方法。相反,只需使用一个数组,并用循环写入其末尾,例如“for (i = 0; i < 1000000; i++) c[i] = 'h';”

关于c - Strcat 堆栈粉碎行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23554887/

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