gpt4 book ai didi

c - C 中结构指针的内存分配和核心转储

转载 作者:行者123 更新时间:2023-11-30 17:51:50 25 4
gpt4 key购买 nike

抱歉,我对内存分配和结构很陌生(所以很可能这是我错过的一些愚蠢的事情)。我有以下代码,它是 Solaris 上的核心转储。我也不确定稍后如何添加更多元素(我应该重新分配内存吗?)

 enum field_type
{
FLD_STRING,
FLD_SHORT
};


typedef struct {
long id;
char *name;
field_type type;
void *value;
} myStruct_t ;

typedef struct {
long id;
const char *name;
field_type type;
const char *descr;
} myStructDef_t;

myStructDef_t Alldef[] =
{
{0, "FirstField", FLD_STRING, "First Field Of Structure"},
{1, "SecondField", FLD_STRING, "Second Field Of Structure"},
{-1}
};


int main()
{
myStruct_t *p_struct;
char tmp[100] = {'\0'};
long id = 0;

if(NULL == (p_struct= structAlloc(1024)))
{
print("Failed allocating memory\n");
return 0;
}
sprintf(tmp, "Test Adding value");
addValueToStruct(p_struct, id, (void *)tmp);

}

myStruct_t *structAlloc(long size)
{
myStruct_t *tmp = (myStruct_t *) calloc(size, sizeof *tmp);
if(NULL != tmp)
tmp->id = -1;
return tmp;
}

int addValueToStruct(myStruct_t *p_struct, long id, (void *)value)
{
myStruct_t *bkStruct = p_struct;
myStructDef_t *def = NULL;

if(-1 == getIdDefinition(def, id))
{
printf("Failed to find definition for id [%ld]", id);
return -1;
}

// Core dumping on 1st line below
bkStruct->id = def->id;
sprintf(bkStruct->name, "%s", def->name);
bkStruct->type = def->def->type;
if(FLD_SHORT == bkStruct->type)
memcpy(bkStruct->value, value, sizeof(*(short *)value));
else if(FLD_STRING == bkStruct->type)
memcpy(bkStruct->value, value, sizeof(*(char *)value));

return 0;
}

int getIdDefinition(myStructDef_t *def, long id)
{
myStructDef_t *AllDefsTmp = Alldef;
bool found = false;

while( -1 != AllDefsTmp->id)
{
if(id == AllDefsTmp->id)
{
def = AllDefsTmp;
found = true;
break;
}
AllDefsTmp ++;
}

if(!found)
return -1;

return 0;

}

谢谢:)

最佳答案

myStructDef_t *def = NULL;

if(-1 == getIdDefinition(def, id))
{
printf("Failed to find definition for id [%ld]", id);
return -1;
}

// Core dumping on 1st line below
bkStruct->id = def->id;

调用 GetIdDefinition(def, id) 将填充该函数中的 def,但不会更改 addValueToStruct 中的值函数 - 您需要一个双指针(在 C 中)或引用(在 C++ 中),以便您可以更改 def 本身的值。 (或者您当然可以只返回找到的值,而不是 -10 返回值)。

关于c - C 中结构指针的内存分配和核心转储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16502311/

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