malloc(sizeof(struct xxxx))没有分配任何内存

ROO*_*DAY 3 c struct memory-management

我正在使用Learn C the Hard Way在线书籍学习C,练习17,我遇到了一个令人困惑的错误.在练习中,我被告知使用malloc(sizeof(struct xxxx))为连接和数据库分配内存,如下所示:

struct Connection *conn = malloc(sizeof(struct Connection));
if(!conn) die("Memory error");

conn->db = malloc(sizeof(struct Database));
if(!conn->db) die("Memory error");
Run Code Online (Sandbox Code Playgroud)

当我运行程序时,我得到一个分段错误,然后在valgrind下运行它后,我收到此错误:

==5770== Command: ./ex17 db.dat c
==5770== 
==5770== Invalid read of size 1
==5770==    at 0x40C4130: _IO_file_fopen@@GLIBC_2.1 (fileops.c:267)
==5770==    by 0x40B88CA: __fopen_internal (iofopen.c:90)
==5770==    by 0x40B893A: fopen@@GLIBC_2.1 (iofopen.c:103)
==5770==    by 0x8048861: Database_open (ex17.c:58)
==5770==    by 0x8048C4C: main (ex17.c:156)
==5770==  Address 0x77 is not stack'd, malloc'd or (recently) free'd
Run Code Online (Sandbox Code Playgroud)

main中的第156行只是通过函数创建一个新的连接结构struct Connection *conn = Database_open(filename, action);,这似乎不是问题.跟随它到达Database_open中的第58行是conn->file = fopen(filename, 'w');从错误的非堆栈,malloc'd部分,我假设上面的mallocs是问题.有人可以确认/帮我解决这个问题吗?

完整代码

Cor*_*lks 10

你的问题是你的问题fopen.本mode应该是一个字符串,而不是一个char.将模式更改为"r+""w".

此外,编译时启用了更多警告.

  • 您在segfault转储中从"地址0x77"(带有"0x77 =='w'`)计算出来了吗?太好了! (3认同)