c - malloc(sizeof(struct xxxx)) isn't allocating any memory -
i'm learning c using learn c hard way online book, on exercise 17, , i've come across confusing error. in exercise, i'm told allocate memory connection , database using malloc(sizeof(struct xxxx)), 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 run program, segmentation fault, after running under valgrind, error:
==5770== command: ./ex17 db.dat c ==5770== ==5770== invalid read of size 1 ==5770== @ 0x40c4130: _io_file_fopen@@glibc_2.1 (fileops.c:267) ==5770== 0x40b88ca: __fopen_internal (iofopen.c:90) ==5770== 0x40b893a: fopen@@glibc_2.1 (iofopen.c:103) ==5770== 0x8048861: database_open (ex17.c:58) ==5770== 0x8048c4c: main (ex17.c:156) ==5770== address 0x77 not stack'd, malloc'd or (recently) free'd
line 156 in main creating new connection struct through function struct connection *conn = database_open(filename, action);
, , doesn't seem issue. following line 58 in database_open conn->file = fopen(filename, 'w');
not stack'd, malloc'd part of error, assumed mallocs above issue. can confirm/help me fix this?
your problem fopen
call. mode
supposed string, not char
. change mode "r+"
or "w"
.
also, compile more warnings enabled.
Comments
Post a Comment