简体   繁体   English

malloc段错误

[英]malloc seg fault

I wrote a function to allocate memory for 2 double variables. 我编写了一个为2个双变量分配内存的函数。 It works when the required memory size is small, but causes seg fault when the required memory grows relatively big. 当所需的内存大小较小时,它可以工作,但是当所需的内存变得相对较大时,则会导致段错误。 Is there any error or bad practise in the written codes? 书面代码中是否有任何错误或不当行为?

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);
}

I get two types of runtime error, either malloc failed, or invalid pointer when free().... 我遇到两种类型的运行时错误,要么malloc失败,要么当free()时指针无效。

error 1: 错误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.`

error 2: 错误2:

*** glibc detected *** ./pt: free(): invalid pointer: 0x0b302ba8 ***

I suspect you are not passing the actual size required and overflowing the double array. 我怀疑您没有通过所需的实际大小并且溢出了双精度数组。 It would be clear when you paste the qsort code, but most likely in your comparison function you would be comparing two doubles and a double takes 8 bytes where as malloc allocates as many bytes passed as an argument. 粘贴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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM