[英]malloc seg fault
我編寫了一個為2個雙變量分配內存的函數。 當所需的內存大小較小時,它可以工作,但是當所需的內存變得相對較大時,則會導致段錯誤。 書面代碼中是否有任何錯誤或不當行為?
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代碼時會很清楚,但是最有可能在比較函數中,您將比較兩個double,而double需要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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.