gpt4 book ai didi

c - strncpy 的问题以及如何修复它

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

我正在学习 C 并正在阅读 Learn C The Hard Way (ISBN-10: 0-321-88492-2)。我被困在练习 17“如何打破它”上。

这是书中的问题:

There is a bug in this program because of strncpy being poorly designed. Go read about strncpy then try to find out what happens when the name or address you give is greater than 512 bytes. Fix this by simply forcing the last character to '\0' so that it's always set no matter what (which is what strncpy should do).

我阅读了一些关于 strncpy 的资料,我知道它是不安全的,因为它不会在字符串末尾添加空字节。但是,我不知道如何将大量字节传递给函数,也不知道如何解决空字节问题。

下面是使用 strncpy 的函数,MAX_DATA 设置为 512。

void Database_set(struct Connection *conn, int id, const char *name, const char *email)
{
struct Address *addr = &conn->db->rows[id];
if(addr->set) die("Already set, delete it first");

addr->set = 1;
// WARNING: bug, read the "How To Break It" and fix this
char *res = strncpy(addr->name, name, MAX_DATA);
// demonstrate the strncpy bug
if(!res) die("Name copy failed");

res = strncpy(addr->email, email, MAX_DATA);
if(!res) die("Email copy failed");
}

如何打破它 - 编辑

下面是一个如何破解 strncpy 的例子:

void Database_set(struct Connection *conn, int id, const char *name, const char *email)
{
struct Address *addr = &conn->db->rows[id];
if(addr->set) die("Already set, delete it first");

addr->set = 1;
// WARNING: bug, read the "How To Break It" and fix this

char name2[] = {
'a', 's', 't',
'r', 'i', 'n', 'g'
};
char *res = strncpy(addr->name, name2, MAX_DATA);
// demonstrate the strncpy bug
if(!res) die("Name copy failed");

res = strncpy(addr->email, email, MAX_DATA);
if(!res) die("Email copy failed");
}

要修复,请在字符串末尾添加一个空字节。将 name2 更改为:

  char name2[] = {
'a', 's', 't',
'r', 'i', 'n', 'g', '\0'
};

或者,在 strncpy 函数调用上方添加以下行

names2[sizeof(names2)-1] = '\0';

最佳答案

修复 strncpy bug 的另一种方法是修复 printf打电话

void Address_print(struct Address *addr)
{
printf("%d %.*s %.*s\n",
addr->id, sizeof(addr->name), addr->name, sizeof(addr->email), addr->email);
}

这限制了 printf 最多输出整个字符数组,但不能更多。

关于c - strncpy 的问题以及如何修复它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21210293/

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