Heap Corruption with malloc, struct and char *

2019-08-03 06:47发布

I seem to have a memory corruption in my C program. I used _ASSERTE( _CrtCheckMemory( ) ); to find the problem statement and it breaks on a line that says scep_conf->engine_str = NULL; right before it. So if I understood it correctly, the malloc before that broke something, right?

So this is the part of the code that causes the issue:

scep_conf = (SCEP_CONF *) malloc(sizeof(scep_conf));
scep_conf->engine = (struct scep_engine_conf_st *) malloc(sizeof(struct scep_engine_conf_st));
scep_conf->engine_str = NULL;

The definitions from the header:

typedef struct {
    struct scep_engine_conf_st *engine;
    char *engine_str;
} SCEP_CONF;

struct scep_engine_conf_st{
    char *engine_id;
    char *new_key_location;
    int storelocation; 
    char *dynamic_path;
    char *module_path; 
    int engine_usage;
};

SCEP_CONF *scep_conf;

Basically I don't get why it would corrupt my memory here. I am new to C and so there may be something obvious I am not seeing.

Any help will be greatly appreciated, thank you.

1条回答
可以哭但决不认输i
2楼-- · 2019-08-03 07:29

This is incorrect:

scep_conf = (SCEP_CONF *) malloc(sizeof(scep_conf)); 

as it only allocates enough memory for a SCEP_CONF*, not a SCEP_CONF. it should be:

scep_conf = malloc(sizeof(*scep_conf)); /* cast unnecessary. */

Worth reading Do I cast the result of malloc?

查看更多
登录 后发表回答