malloc 和free可以不在一个函数里,只要free里面传递malloc返回的地址就可以了。
在一些成熟的软件包中分配空间和释放空间也经常不在同一个函数里,这样的例子有readline函数库,gtk图形库等,分配资源和释放资源不可能放在同一个函数里。
如果malloc分配的内存不被free函数释放掉,那么会在进程结束时还给操作系统。以下是glibc手册对free的说明:
There is no point in freeing blocks at the end of a program, because all of the program's space is given back to the system when the process terminates.
没有必要在程序末尾释放内存块,因为在进程结束时程序的所有内存空间都归还给操作系统了。