gpt4 book ai didi

c - malloc 段错误

转载 作者:行者123 更新时间:2023-11-30 15:55:00 25 4
gpt4 key购买 nike

我编写了一个函数来为 2 个 double 变量分配内存。当所需的内存大小较小时,它可以工作,但当所需的内存增长相对较大时,会导致段错误。编写的代码是否有任何错误或不良做法?

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 ***

最佳答案

我怀疑您没有传递所需的实际大小并溢出 double 组。当您粘贴 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));

关于c - malloc 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12615526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com