malloc(sizeof(struct xxxx)) isn't allocating any memory

c, memory-management, struct

Solution

Your problem is your `fopen` call. The `mode` is supposed to be a string, not a `char`. Change the mode to `"r+"` or `"w"`.

Also, compile with more warnings enabled.

Problem

I'm learning C using the Learn C the Hard Way online book, on exercise 17, and I've come across a confusing error. In the exercise, I'm told to allocate the memory for a connection and database using malloc(sizeof(struct xxxx)), like so: ``` struct Connection *conn = malloc(sizeof(struct Connection)); if(!conn) die("Memory error"); conn->db = malloc(sizeof(struct Database)); if(!conn->db) die("Memory error"); ``` When I run the program, I get a Segmentation Fault, then after running it under valgrind, I get this error: ``` ==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 ``` Line 156 in main is simply creating a new connection struct through a function `struct Connection *conn = Database_open(filename, action);`, and that doesn't seem to be the issue. Following it up to the line 58 in Database_open is `conn->file = fopen(filename, 'w');` From the not stack'd, malloc'd part of the error, I assumed the mallocs above were the issue. Can someone confirm/help me fix this? Full code

Original source