简体   繁体   中英

Free dynamic memory getting error

I am having a problem of freeing dynamic memory. I have run other guy's example code, and it worked. The point is we used same way to free memory, but mine didn't work. It always comes out a error that

"CRT detected that the application wrote to memory after end of heap buffer. "

Could anyone help me understand what happened?

void pop(Stackptr *ptr){
    Stackptr tmp = NULL;
    if(*ptr == NULL){
        printf("there is no element\n");
    }else{
        tmp = *ptr;
        *ptr= (*ptr)->nextptr;
        free(tmp);
    }
}

As I can see, the error is

 tmp = *ptr;

You want the pointer itself to be stored int tmp , not the value.

Thus, the next free(tmp); becomes illegal, as the pointer you're passing is invalid . Calling free() on a pointer that is not previously returned by malloc() and family or already free() -d, invokes undefined behavior .

That said, if(*ptr == NULL) should be if(ptr == NULL) , to check the NULL-value of the pointer.

Moral of the story: Enable compiler warnings. Try to fix the issues for which your compiler issues a warning.

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