Does memory allocated in a function still stay allocated after the function returns?

后端 未结 7 2028
鱼传尺愫
鱼传尺愫 2021-02-04 06:57

For the code below: (1) \"main\" calls a function \"f1\". (2) function \"f1\" does some number crunching; creates an array of \"char\" with mal

7条回答
  •  终归单人心
    2021-02-04 07:14

    If you don't free memory you're not using, eventually this would accumulate- if you done this with many other pointers- and your program could run out of memory. After freeing a memory block using the free function, I'd also suggest assigning NULL to the pointer as this protects against dangling pointers as even if you've freed a pointer, if you try accessing it, you could get undefined behaviour, whereas access and operations on NULL pointers result in a crash, so you'd easily be able to trace the problem

提交回复
热议问题