简体   繁体   English

为什么我可以分配局部变量并对其进行读取,但是如果我尝试在结构中分配指针并对其进行读取,则会出现段错误?

[英]Why can I allocate a local variable and fread to it, but segfault if I try to allocate a pointer in a struct and read to it?

I'm playing with a small C program to brush up. 我正在玩一个小的C程序来刷牙。 I have the following struct... 我有以下结构...

struct Address {
    int id;
    int set;
    char *name;
    char *email;
};

I am trying to read some data into it. 我正在尝试向其中读取一些数据。 This works: 这有效:

size_t len = 256 * sizeof(char);

struct Address *thisAddress = malloc(sizeof(struct Address));
char *name = malloc(len);
char *email = malloc(len);

rc = fread(thisAddress, sizeof(struct Address), 1, conn->file);
if(rc != 1) die("Failed to load address.", conn);

rc = fread(name, len, 1, conn->file);
if(rc != 1) die("Failed to load name.", conn);

rc = fread(email, len, 1, conn->file);
if(rc != 1) die("Failed to load email.", conn);

thisAddress->name = name;
thisAddress->email = email;
conn->db->rows[i] = thisAddress;

But this segfaults: 但这段错误:

size_t len = 256 * sizeof(char);
struct Address *thisAddress = malloc(sizeof(struct Address));
thisAddress->name = malloc(len);
thisAddress->email = malloc(len);

rc = fread(thisAddress, sizeof(struct Address), 1, conn->file);
if(rc != 1) die("Failed to load address.", conn);

rc = fread(thisAddress->name, len, 1, conn->file);
if(rc != 1) die("Failed to load name.", conn);

rc = fread(thisAddress->email, len, 1, conn->file);
if(rc != 1) die("Failed to load email.", conn);

conn->db->rows[i] = thisAddress;

If you can't see it right away, in the first one I'm malloc'ing the name and edit vars, reading from the file into those vars, then assigning them to the name and email pointers on struct Address. 如果您不能立即看到它,则在第一个中,我要分配名称并编辑var,将文件读入这些var,然后将其分配给struct Address上的名称和电子邮件指针。 In the second, I'm trying to alloc the pointers on struct Address, and read directly into them. 在第二篇文章中,我试图在struct Address上分配指针,并直接读取它们。

Why would these two be different? 为什么这两个会有所不同? Any insight is helpful, thanks! 任何见解都是有帮助的,谢谢!

First you do 首先你要做

thisAddress->name = malloc(len);
thisAddress->email = malloc(len);

Then you do 那你做

rc = fread(thisAddress, sizeof(struct Address), 1, conn->file);

This reading of the structure overwrites the pointers you previously set. 对结构的读取将覆盖您先前设置的指针。 So the pointers you use to read the name and email address texts from the file are not the ones you allocated, but the ones you read from the file, which are very unlikely to point to any valid memory, leading to undefined behavior . 因此,用于从文件读取名称和电子邮件地址文本的指针不是您分配的指针,而是您从文件读取的指针,它们不太可能指向任何有效的内存,从而导致未定义的行为

If you change the order of the first structure read and the allocations it should work. 如果您更改第一个结构的读取顺序和分配,则它应该起作用。

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

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