2012-07-26 116 views
1

我的C程序中似乎有内存损坏。我使用_ASSERTE(_CrtCheckMemory());来查找问题陈述,并且在它之前的一行上写着scep_conf->engine_str = NULL;。所以,如果我正确地理解了它,那么malloc在破解之前就是对的?malloc,struct和char堆腐败*

所以这是部分代码导致问题:

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; 

从标题中的定义:

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; 

基本上我不知道为什么它会破坏我的记忆在这里。我是C新手,所以可能有一些明显的我没有看到。

任何帮助将不胜感激,谢谢。

回答

6

这是不正确的:

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

,因为它只是一个SCEP_CONF*,不是SCEP_CONF分配足够的内存。它应该是:

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

值得一读Do I cast the result of malloc?

+0

非常\不错赶上! – MByD 2012-07-26 10:06:23

+0

很好的答案。指针或不指针... – logoff 2012-07-26 10:06:54

+0

谢谢*非常*! – javex 2012-07-26 10:43:22