简体   繁体   English

struct中的字符串。 损坏

[英]String in struct. corrupted

There is struct like this. 有像这样的结构。

struct Address {
    int id;
    int set;
    char name[MAX_DATA];
    char email[MAX_DATA];
};

And function which set's address. 和设置地址的功能。

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("Address already set");

    addr->set = 1;
    char *res = strncpy(addr->name, name, MAX_DATA);
    if(!res) die("Name copy failed");

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

But first character of addr->name gets corrupted after this line. 但是addr-> name的第一个字符在此行之后被破坏了。

*res = strncpy(addr->email, email, MAX_DATA);

Any ideas? 有任何想法吗?

strncpy returns its first argument so after strncpy返回它的第一个参数

char *res = strncpy(addr->name, name, MAX_DATA);

the variable res holds addr->name (equivalently, &(addr->name[0]) ) so when 变量res保存addr->name (等效地, &(addr->name[0]) )所以当

*res = strncpy(addr->email, email, MAX_DATA);

is run it is the equivalent of 运行它相当于

addr->name[0] = strncpy(addr->email, email, MAX_DATA);

This assignment is what corrupts the first char of addr->name . 这个赋值是破坏addr->name的第一个char。 As Greg Hewgill says, you don't need to check or even save the return value of strncpy . 正如Greg Hewgill所说,你不需要检查甚至保存strncpy的返回值。

I think the strncpy() function is not what you want here. 我认为strncpy()函数不是你想要的。 Consider the call: 考虑一下电话:

strncpy(addr->name, name, MAX_DATA);

In the event that name has MAX_DATA or more characters, this will copy the bytes from name into addr->name and will not NUL-terminate the destination. 如果name具有MAX_DATA或更多字符,则会将name的字节复制到addr->name并且不会 NUL终止目标。 You have two general choices: 您有两个一般选择:

  1. Manually NUL-terminate the result using code such as 手动NUL使用诸如的代码终止结果

     addr->name[MAX_DATA-1] = '\\0'; 

    however, this is error-prone because you have to remember to do it each time. 但是,这很容易出错,因为每次都必须记住这样做。

  2. Use a library function such as strlcpy() (usually available on BSD-derived systems, but not standard) that always NUL-terminates the destination, even if the source won't completely fit. 使用库函数,例如strlcpy() (通常在BSD派生的系统上可用,但不是标准的),总是NUL终止目标,即使源不完全适合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM