gpt4 book ai didi

c - C 中 strncpy 的内存混淆

转载 作者:太空狗 更新时间:2023-10-29 15:23:29 25 4
gpt4 key购买 nike

本周我的同事讨论了一个关于内存的问题:

示例代码 1:

int main()
{
#define Str "This is String."
char dest[1];
char buff[10];

strncpy(dest, Str, sizeof(Str));
printf("Dest: %s\n", dest);
printf("Buff: %s\n", buff);
}

输出:

Dest: This is String.
Buff: his is String.

示例代码 2:

int main()
{
#define Str "This is String."
char dest[1];
//char buff[10];

strncpy(dest, Str, sizeof(Str));
printf("Dest: %s\n", dest);
//printf("Buff: %s\n", buff);
}

输出:

Dest: This is String.
*** stack smashing detected ***: ./test terminated
Aborted (core dumped)

我不明白为什么我会在案例 1 中得到该输出?因为 buff 甚至没有在 strncpy 中使用,如果我评论变量 buff,它将检测到堆栈粉碎,但输出为 dest。 另外对于 buff 为什么我将输出作为“his as string”。

最佳答案

这是一个有趣的问题,我们都希望在某个时候了解它。此处发生的问题称为“缓冲区溢出”。此问题的副作用因系统而异(也称为未定义行为)。只是为了向您解释您的情况可能发生的情况,我们假设您程序中变量的内存布局如下

enter image description here

注意上面的表示只是为了理解,并不显示任何架构的实际表示。strncpy命令执行后,该内存区域的内容如下

enter image description here

现在,当您打印 buff 时,您可以看到 buf 的起始地址现在包含“h”。 printf 开始打印它,直到它找到一个超出 buff 内存区域的空字符。因此,当您打印 buf 时,您会得到 'his is String'。但是请注意,程序 1 不会生成堆栈粉碎错误,因为堆栈保护(这是系统/实现)相关。因此,如果您在不包含此代码的系统上执行此代码,程序 1 也会崩溃(您可以通过将 Str 增加到一个长字符串来测试此代码)。

在程序 2 的情况下,strncpy 只是越过堆栈守卫并写入来自 main 的返回地址,因此您会发生崩溃。

希望这对您有所帮助。

附言以上描述仅供理解,不代表任何实际系统。

关于c - C 中 strncpy 的内存混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41158314/

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