简体   繁体   中英

malloc seg fault

I wrote a function to allocate memory for 2 double variables. 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()....

error 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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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