-2

Sorry for asking this question, I have tried to find the solution on stackoverflow, but no satisfying result. My code is as the following, thanks for your patience.

#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;
}
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
HuangJie
  • 1,488
  • 1
  • 16
  • 33

1 Answers1

6

You never allocate space for comp->highest_committed_vs and you check comp for NULL after dereferencing it. Try like this

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;
}
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97