分段错误(malloc结构)
很抱歉问这个问题,我试图找到stackoverflow的解决方案,但没有令人满意的结果。我的代码如下,谢谢你的耐心分段错误(malloc结构),c,malloc,C,Malloc,很抱歉问这个问题,我试图找到stackoverflow的解决方案,但没有令人满意的结果。我的代码如下,谢谢你的耐心 #include <inttypes.h> #include <stdlib.h> #include <malloc.h> #include <memory.h> #include <string.h> typedef uint32_t req_id_t; typedef uint32_t view_id_t; type
#include <inttypes.h>
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <string.h>
typedef uint32_t req_id_t;
typedef uint32_t view_id_t;
typedef uint64_t db_key_type;
typedef struct view_stamp_t {
view_id_t view_id;
req_id_t req_id;
}view_stamp;
typedef struct consensus_component_t {
view_stamp* highest_committed_vs;
}consensus_component;
uint64_t vstol(view_stamp* vs) {
uint64_t result = ((uint64_t)vs->req_id)&0xFFFFFFFFl;
uint64_t temp = (uint64_t)vs->view_id&0xFFFFFFFFl;
result += temp<<32;
return result;
}
int main() {
consensus_component* comp = (consensus_component*)malloc(sizeof(consensus_component));
memset(comp, 0, sizeof(consensus_component));
if(NULL != comp) {
comp->highest_committed_vs->view_id = 1;
comp->highest_committed_vs->req_id = 0;
db_key_type start = vstol(comp->highest_committed_vs)+1;
printf("%" PRIu64 "\n", start);
}
return 0;
}
#包括
#包括
#包括
#包括
#包括
类型定义uint32请求id;
typedef uint32\u t视图\u id\t;
typedef uint64\u t db\u key\u type;
类型定义结构视图\u戳记\u t{
查看\u id\u t查看\u id;
请求id请求id;
}查看(u)邮票;;
类型定义结构一致性组件{
查看印章*最高承诺金额;
}协商一致意见构成部分;
uint64\u t vstol(查看邮票*vs){
uint64_t结果=((uint64_t)vs->req_id)&0xFFFFFFFFl;
uint64_t temp=(uint64_t)vs->view_id&0xFFFFFFFFl;
结果+=tempview_id=1;
comp->highest\u committed\u vs->req\u id=0;
db_key_type start=vstol(comp->highest_committed_vs)+1;
printf(“%”PRIu64“\n”,开始);
}
返回0;
}
您从不为comp->highest\u committed\u vs
分配空间,并且在取消引用后检查comp
是否为NULL
。像这样试试
int main()
{
consensus_component *comp = malloc(sizeof(consensus_component));
if (comp == NULL)
return -1;
memset(comp, 0, sizeof(consensus_component));
comp->highest_committed_vs = malloc(sizeof(*comp->highest_committed_vs));
if (comp->highest_committed_vs == NULL)
{
free(comp);
return -1;
}
comp->highest_committed_vs->view_id = 1;
comp->highest_committed_vs->req_id = 0;
db_key_type start = vstol(comp->highest_committed_vs)+1;
printf("%" PRIu64 "\n", start);
return 0;
}
malloc()。我通过添加comp->highest\u committed\u vs=(view\u stamp*)malloc(sizeof(view\u stamp))
@HuangJie请删除malloc()的演员阵容。