我写了一个函数为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 ***
答案 0 :(得分:1)
我怀疑你没有传递所需的实际大小并且溢出了双数组。当你粘贴qsort代码时会很清楚,但很可能在你的比较函数中,你将比较两个双精度数,一个double需要8个字节,其中malloc分配了作为参数传递的 bytes 。< / p>
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));