0

我是 C 新手,使用 Zed Shaw 的 Learn C the Hard Way 进行学习。我在找出为什么会出现以下内存错误时遇到了一些麻烦。我很确定我没有泄漏内存,因为我使用 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;
    };

这是我使用的 die 函数:

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;
};
4

2 回答 2

2
struct Connection *conn = malloc(sizeof(struct Connection));

if(!conn->db) die("Memory Error"); // ?

您期望在不设置新创建变量conn->db的内容的情况下成为非零值。conn也许那个地方偶然有一个零。请记住,使用malloc()不能保证返回的内存的初始内容是什么。

于 2012-09-06T18:49:07.337 回答
1

感谢您提供有关结构的详细信息Connection。如所见,该结构包含两个指针元素作为成员。

分配结构后,您必须专门malloc指定其中的元素Database *db

就像是:

struct Connection *conn= malloc(sizeof(struct Connection));
conn->db = malloc(sizeof(struct Database));

希望这可以帮助。

于 2012-09-06T19:02:41.150 回答