【发布时间】:2018-11-30 15:19:37
【问题描述】:
我的程序是一个命令行数据库程序。这是一个迷你的。您可以在数据库中创建实体。命令就像“创建实体名称”。我在创建实体函数时遇到了问题。
我为我的结构数组重新分配内存。只是我在扩张。但是在第二次扩展之后,我丢失了扩展数组的第二个元素(ankara)的字符数组。我们来看代码;
void task_create_entity(char* name)
{
int status;
ENTITY *e = create_entity(name, &status);
if(e)
{
if(db->entities == NULL)
{
db->entities = new_entity_list(4);
db->list_size = 4;
db->entities[0] = e;
db->size = 1;
}
else
{
int old_list_size = db->list_size;
if(db->size >= db->list_size)
{
ENTITY **temp = expand_entity_list(db->entities, &db->list_size);
if(temp != NULL)
{
if(db->entities != temp)
db->entities = temp;
}
else
{
printf("Operating system did not allocate memory, entities list could not expanded\n");
drop_entity(e);
db->list_size = old_list_size;
return;
}
}
db->entities[db->size++] = e;
}
task_list_entities();
}
else
{
if(status == 1)
{
printf("Already exists a entity in database with this name\n");
}
else if(status == 2)
{
printf("Entity file could not created\n");
}
}
}
此函数创建实体并在 DB(struct) 中附加数组。如果数组大小很小,我的函数会扩展它并附加它。在创建新实体后,我正在使用 task_list_entities() 函数打印我的实体名称。控制台输入和输出是:
CREATE ENTITY istanbul
istanbul
CREATE ENTITY ankara
istanbul
ankara
CREATE ENTITY seul
istanbul
ankara
seul
CREATE ENTITY monako
istanbul
ankara
seul
monako
CREATE ENTITY manchester
istanbul
ankara
seul
monako
manchester
CREATE ENTITY paris
istanbul
ankara
seul
monako
manchester
paris
CREATE ENTITY lizbon
istanbul
ºÖW
seul
monako
manchester
paris
lizbon
列表以 4 个元素开始并扩展为 4, 6, 9, 13, ... 这是扩展代码:
ENTITY** expand_entity_list(ENTITY** entities, uint32_t* size)
{
*size = *size + (*size / 2);
return (ENTITY**) realloc(entities, *size);
}
在第二次扩展操作之后,我失去了第二个实体(安卡拉)的名称。
ENTITY* create_entity(char* name, int* status)
{
ENTITY *entity = (ENTITY*) malloc(sizeof(ENTITY));
entity->file = NULL;
entity->name = duplicate_string(name);
entity->records = NULL;
entity->size = 0;
entity->commited = 0;
*status = 0;
return entity;
}
这是新的实体列表功能:
ENTITY** new_entity_list(uint32_t size)
{
return (ENTITY**) malloc(sizeof(ENTITY*) * size);
}
这是字符串复制功能:
char* duplicate_string(char* origin)
{
char *dup = (char*) malloc(sizeof(char) * (strlen(origin) + 1));
strcpy(dup, origin);
return dup;
}
结果我找不到错误的原因。实体的其他价值不会丢失。只是 char* 名称。这是实体结构:
typedef struct entity
{
char *name;
FILE *file;
RECORD **records;
int size;
uint8_t commited;
} ENTITY;
【问题讨论】:
-
您的问题中缺少一些重要部分 - 例如。
new_entity_list和duplicate_string是如何实现的?请创建一个minimal, complete and verifiable example。 -
我尝试过细化。我在下次访问时遇到分段错误错误,因为我在展开后丢失了 char 数组的地址。