Calling free on a pointer twice

前端 未结 4 1287
轻奢々
轻奢々 2021-02-04 03:07

I have been taught in lectures, that calling free() on a pointer twice is really, really bad. I know that it is good practice, to set a pointer to NULL

4条回答
  •  后悔当初
    2021-02-04 03:32

    When you use malloc you are telling the PC that you want to reserve some memory location on the heap just for you. The computer gives back a pointer to the first byte of the addressed space.

    When you use free you are actually telling the computer that you don't need that space anymore, so it marks that space as available for other data.

    The pointer still points to that memory address. At this point that same space in the heap can be returned by another malloc call. When you invoke free a second time, you are not freeing the previous data, but the new data, and this may not be good for your program ;)

提交回复
热议问题