分段错误(malloc struct)

时间:2016-01-10 16:15:56

标签: 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;
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;
}

1 个答案:

答案 0 :(得分:6)

您永远不会为comp->highest_committed_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;
}