gpt4 book ai didi

c - 无法初始化结构数组

转载 作者:行者123 更新时间:2023-11-30 15:06:39 25 4
gpt4 key购买 nike

我正在尝试使用 memset 初始化 struct 类型的数组单元。该程序成功编译,但是 Valgrind 对与 memseting 这些单元格相关的事情不满意。注释掉的代码也不起作用。

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#define MAX_DATA 512
#define MAX_ROWS 100



struct Address {
int id;
int set;
char name[MAX_DATA];
char email[MAX_DATA];
};

struct Database{
struct Address rows[MAX_ROWS];
};

struct Connection{
FILE* file;
struct Database* db;
};


void die(const char* message)
{
if(errno){
perror(message);
}else{
printf("ERROR: %s\n", message);
}
exit(1);
}



void Database_load(struct Connection* conn)
{
int rc = fread(conn->db, sizeof(struct Database), 1, conn->file);
if (rc != 1)
{
die("Failed to load database.");
}
}


struct Connection* Database_open(const char* filename, char mode)
{
struct Connection* conn = malloc(sizeof(struct Connection));
if (!conn)
{
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 Database_create(struct Connection* conn)
{
int i = 0;

for(i = 0; i < MAX_ROWS; i++) {
//struct Address addr = {.id = i, .set = 0};
//conn->db->rows[i] = addr;
memset(&(conn->db->rows[i]), 0, sizeof(struct Address));
conn->db->rows[i].id = i;
}
}




int main(int argc, char* argv[])
{
if(argc < 3) die("USAGE: ex17 <dbfile> <action> [action params]");

char* filename = argv[1];
char action = argv[2][0];
struct Connection* conn = Database_open(filename, action);
int id = 0;
if(argc > 3) id = atoi(argv[3]);
if(id >= MAX_ROWS) die("There's not that many records.");


Database_create(conn);

return 0;
}

相关的 Valgrind 错误 -

==16227== Conditional jump or move depends on uninitialised value(s)
==16227== at 0x4C3009C: memset (vg_replace_strmem.c:1224)
==16227== by 0x400BA8: Database_create (ex17.c:108)
==16227== by 0x400EE1: main (ex17.c:174)

最佳答案

您的代码永远不会初始化conn->db

你需要这样的东西:

conn->db = malloc(sizeof(struct Database));
if (!conn->db)
{
die("Memory error");
}

Database_open函数内部

关于c - 无法初始化结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38917583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com