You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

需删除其他函数/类方法返回的指针吗?Java背景者的C++内存疑问

Understanding Memory Management for Library-Returned Pointers (From Java to C/C++)

Hey there! Totally get the confusion switching from Java—memory management in C/C++ is way more manual, so no need to apologize for "basic" questions at all. Let's break down your specific scenario and the general rules you need to follow.

First, a Critical Rule to Remember

Never use delete (or delete[]) to free memory you didn’t allocate with new (or new[]).

  • C-style memory allocation (like malloc, calloc) uses free() to release memory.
  • Library functions almost always provide their own dedicated cleanup functions for pointers they return—you can’t just guess which method to use.

Let’s Break Down Your Example

You mentioned DIR* dir from opendir() and struct dirent* entries from readdir():

1. DIR* dir from opendir()

This pointer points to an internal structure managed by the directory handling library. You must not use delete dir to free it. Instead, use the dedicated cleanup function: closedir(dir).

closedir() doesn’t just free the memory for the DIR structure—it also cleans up underlying resources (like file descriptors) that opendir() opened. Using delete here would cause undefined behavior (crashes, memory corruption, etc.) because the memory wasn’t allocated with new.

2. struct dirent* entries from readdir()

This one is a bit trickier: the pointer returned by readdir() points to a static internal buffer maintained by the library. This means:

  • You do NOT need to free this pointer yourself (calling free() or delete on it will crash your program).
  • Every time you call readdir(), this buffer gets overwritten with the next directory entry’s data. If you need to keep the data (like the filename), you have to make a copy of it (e.g., using strdup() or malloc() + memcpy()), and then you’re responsible for freeing that copied memory.

A Correct Example of Usage

Here’s how your code should look to avoid leaks and crashes:

#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    DIR* dir = opendir("D:/DIR");
    if (!dir) {
        perror("Failed to open directory");
        return 1;
    }

    struct dirent* entry;
    while ((entry = readdir(dir)) != NULL) {
        // Copy the filename to our own allocated memory
        char* saved_filename = strdup(entry->d_name);
        if (!saved_filename) {
            perror("Failed to allocate memory");
            closedir(dir);
            return 1;
        }

        printf("Found entry: %s\n", saved_filename);
        
        // We allocated this, so we free it
        free(saved_filename);
    }

    // Clean up the DIR* with the correct function
    closedir(dir);
    return 0;
}

General Guidelines for Library-Returned Pointers

  • Always check the function’s documentation: Any library function that returns a dynamically allocated pointer will explicitly tell you how to free it. For example:
    • fopen() → fclose()
    • malloc()/calloc()/realloc() → free()
    • opendir() → closedir()
    • Some functions (like readdir(), getenv()) return pointers to static memory—never free these.
  • "Who allocates, who cleans up": This is the core principle. If you didn’t allocate the memory (via new, malloc, etc.), don’t assume you need to free it. Let the library handle its own memory via its provided cleanup functions.

内容的提问来源于stack exchange,提问作者Cypher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:40:11