加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

strncpy的问题以及如何解决它

发布时间:2020-12-16 10:08:49 所属栏目:百科 来源:网络整理
导读:我正在学习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
我正在学习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 ‘’ 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,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);
    if(!res) die("Email copy failed");
}

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

char name2[] = {
    'a','g',''
  };

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

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

解决方法

修复strncpy错误的另一种方法是修复 printf调用

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读