我是C的新手,并使用Zed Shaw的“学习C艰难之路”进行学习。我找不到为什么会出现以下内存错误。我很确定我没有泄漏内存,因为我使用Valgrind检查我的代码。
以下是我的代码中有问题的行:
: int main(int argc,char *argv[]){
if (argc<3) die ("USAGE : ex17 <dbfile> <action> [action params]");
...char *filename=argv[1];// how are we able to get away with one dimension?
char action =argv[2][0];
/*Line 166*/:struct Connection *conn=Database_open(filename,action);// error throwing line
函数Database_open定义为:
/*Line 61*/:struct Connection *Database_open(const char *filename, char mode)
{
/* data */
struct Connection *conn= malloc(sizeof(struct Connection));
if(!conn->db) die("Memory Error");//?
if(mode=='c'){
conn->file=fopen(filename,"w");
}
else{
conn->file=fopen(filename,"r+");
if(conn->file){
Database_load(conn);
}
}
if(!conn->file) die("Failed to open file");
return conn;
};
这是我使用的模具功能:
void die (const char *message)
{
if(errno){
perror(message);
}
else{
printf("ERROR :%s\n", message);
}
exit(1);
}
当我使用Valgrind运行代码时,我得到:
==6112== Command: ./ex17 db.dat c
==6112==
==6112== Conditional jump or move depends on uninitialised value(s)
==6112== at 0x80487B3: Database_open (ex17.c:61)//Marked above
==6112== by 0x8048BAA: main (ex17.c:166)// Line numbers marked above
==6112==
ERROR :Memory Error
==6112==
==6112== HEAP SUMMARY:
==6112== in use at exit: 8 bytes in 1 blocks
==6112== total heap usage: 1 allocs, 0 frees, 8 bytes allocated
==6112==
==6112== LEAK SUMMARY:
==6112== definitely lost: 0 bytes in 0 blocks
==6112== indirectly lost: 0 bytes in 0 blocks
==6112== possibly lost: 0 bytes in 0 blocks
==6112== still reachable: 8 bytes in 1 blocks
==6112== suppressed: 0 bytes in 0 blocks
==6112== Rerun with --leak-check=full to see details of leaked memory
==6112==
==6112== For counts of detected and suppressed errors, rerun with: -v
==6112== Use --track-origins=yes to see where uninitialised values come from
==6112== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
修改
结构连接
struct Connection
{
/* data */
FILE *file;
struct Database *db;
};
答案 0 :(得分:2)
struct Connection *conn = malloc(sizeof(struct Connection));
if(!conn->db) die("Memory Error"); // ?
如果没有设置新创建的conn->db
变量的内容,您希望conn
为非零值。也许在那个地方偶然出现零。请记住,使用malloc()
,无法保证返回内存的初始内容是什么。
答案 1 :(得分:1)
感谢您提供有关结构Connection
的详细信息。如图所示,该结构包含两个指针元素作为成员。
分配结构后,您必须明确malloc
其中的元素Database *db
。
类似的东西:
struct Connection *conn= malloc(sizeof(struct Connection));
conn->db = malloc(sizeof(struct Database));
希望这有帮助。