代码之家  ›  专栏  ›  技术社区  ›  Weboide

在C中,是否需要在退出时释放指针?[复制品]

  •  4
  • Weboide  · 技术社区  · 14 年前

    Possible Duplicate:
    When you exit a C application, is the malloc-ed memory automatically freed?

    在C语言中,是否需要在出口释放指针? When the program exists, does it free memory from pointers still pointing to an allocated block?

    Is it dependent on the OS?

    5 回复  |  直到 14 年前
        1
  •  9
  •   ssube    14 年前

    据我所知,在大多数情况下,当进程终止时,操作系统将释放任何进程内存,至少在最常见的用户操作系统(Windows、Linux等)下是如此。如果进程崩溃或类似情况,操作系统也将执行清理。

    然而, relying on the OS to perform cleanup is not proper coding procedure and you can't always guarantee it'll do what you want. You should always perform your own garbage collection if you want it done right and at the right time (I've had programs crash during exit because the system cleaned up memory in an odd order and created some invalid pointers, that it then tried to free).

    Process memory cleanup may only apply to memory allocated by your original process or thread. If you spawn new processes, these could keep executing. If you use an already-running service and call some method that allocates memory then gives you control, that may not get cleanup up.

    Some video drivers won't free VRAM immediately and on some older cards, running a process that leaked VRAM repeatedly would eventually crash your system.

        2
  •  6
  •   Jeff Barger    14 年前

    当程序退出时,操作系统将释放程序分配的任何内容。但是,最好的做法是始终释放您分配的内容。

        3
  •  5
  •   Stephen    14 年前

    现代的 OS is going to leak this memory, all the memory used by the process will be reclaimed.

        4
  •  2
  •   wilhelmtell    14 年前

    This is OS-dependent, but really any modern operating system should take back all of your resources when you terminate.

    That said, it's really a good idea to free any memory you acquire if you can -- and in all but few cases you can. Also, remember we're talking about 记忆

        5
  •  -2
  •   stanigator    14 年前

    这取决于操作系统。虽然在大多数情况下,忘记释放指针不会造成太大的伤害,但这样做也不是一个好主意。这会导致 memory leak . 如果发生的时间足够长,您可能会遇到无法访问的奇怪的内存不足,导致其他程序没有足够的内存来运行。

    If you're talking about explicitly freeing a dynamically allocated array that a pointer is pointing to