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.
*res = strncpy(addr->email, email, MAX_DATA);
Any ideas?
strncpyreturns its first argument so afterthe variable
resholdsaddr->name(equivalently,&(addr->name[0])) so whenis run it is the equivalent of
This assignment is what corrupts the first char of
addr->name. As Greg Hewgill says, you don’t need to check or even save the return value ofstrncpy.