memory corruption

前端 未结 7 1035
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-21 19:31

i was running a small c program:

#include
int main()
{
char *p;
p = (char *)malloc(10);
free(p);
free(p);
free(p);
printf(\"\\npointer is freed!!\         


        
相关标签:
7条回答
  • 2021-01-21 19:40

    freeing already freed memory, leads to undefined behavior, you got lucky, in this case, on other times you might get your core-dump

    0 讨论(0)
  • 2021-01-21 19:42

    Just to add to the other answers, I'd like to note that if you set the pointer to NULL and then called free(), the behaviour wouldn't be undefined anymore. It's pretty much a no-op. However, if the pointer is freed and you call free() on it again before assigning the pointer to a different location (even NULL), you can't be sure of what happens. It could result in a core dump on some implementations and nothing would happen on some others.

    0 讨论(0)
  • 2021-01-21 19:52

    I would expect DEBUG builds of most compilers to be able to detect this type of a failure and report exactly what happened. So would MSVC do.

    In RELEASE, it could be optimized to generate unpredictable behavior faster.

    0 讨论(0)
  • 2021-01-21 19:55

    As per the man page, "if free(ptr) has already been called before, undefined behavior occurs."

    It doesn't need to blow up; "not doing anything" is perfectly acceptable undefined behaviour. Also are nasal demons. Don't rely on it.

    0 讨论(0)
  • 2021-01-21 19:56

    It depend on the implementation of your OS (linux, windows...) who implement this function. Their behaviors may be different depending on the OS (undefined behavior), so you must not rely on them and you must free only one time all allocated memory in you program.

    EDIT: it is not part of the OS but of the standard library which differ depending on the OS.

    0 讨论(0)
  • 2021-01-21 19:57

    Heap corruption need not cause the problem immediately. It could so happen that the freed memory ( or part of the memory) is used to allocat some other structure and then it might cause problem. freeing memory more than once is always UB (undefined) and should not be done even if you don't see evil effects at that moment.

    0 讨论(0)
提交回复
热议问题