我写了一个函数来为 2 个双变量分配内存。当所需的内存大小较小时,它起作用,但当所需的内存增长相对较大时,它会导致 seg 错误。编写的代码中是否有任何错误或不良做法?
void RDF_MALLOC(void** p, size_t sz){
*p = malloc(sz);
if (*p == NULL){
RDF_LOG(kERROR, "Insufficient memory.n");
} else {
memset(*p, 0x00, sz);
}
}
void RDF_FREE(void* p){
if (p != NULL){
free(p);
p = NULL;
} else {
RDF_LOG(kERROR, "Fail to free memory.n");
}
}
void calcErr(){
int PTCORE_MAX_SESSION_NODE = 1800;
double* sum_least_square_err = NULL;
double* node_sum_least_square_err = NULL;
RDF_MALLOC((void**)&sum_least_square_err, PTCORE_MAX_SESSION_NODE*PTCORE_MAX_SESSION_NODE);
RDF_MALLOC((void**)&node_sum_least_square_err, PTCORE_MAX_SESSION_NODE);
/* run qsort to sort content in sum_least_square_err , and node_sum_least_square_err...*/
RDF_FREE(sum_least_square_err);
RDF_FREE(node_sum_least_square_err);
}
我得到两种类型的运行时错误,要么是malloc失败,要么是free()时指针无效。
错误 1:
`malloc.c:3096: sYSMALLOc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed.`
错误 2:
*** glibc detected *** ./pt: free(): invalid pointer: 0x0b302ba8 ***
我怀疑您没有通过所需的实际大小并溢出双精度数组。当您粘贴 qsort 代码时会很清楚,但很可能在您的比较函数中,您将比较两个双精度值,而双精度值需要 8 个字节,其中 malloc 分配了作为参数传递的字节数。
RDF_MALLOC((void**)&sum_least_square_err, PTCORE_MAX_SESSION_NODE*PTCORE_MAX_SESSION_NODE * sizeof(double));
RDF_MALLOC((void**)&node_sum_least_square_err, PTCORE_MAX_SESSION_NODE*sizeof(double));