c - 为结构动态分配内存的正确方法是什么?

标签 c windows malloc realloc

我正在开发一个程序,它应该在注册表中搜索特定值,并将它们及其路径存储在一个数组中。所以我不知道程序会找到多少键,因此我需要使用动态增长的数组。我现在正在使用这段代码,但我不确定它是否正确。

struct data
{
char * Path;
char * Key;
};
struct data **RegArray = NULL;

int ArrayCount = 0;

// ....
// ....

// search the registry here....

// value has been found, so i should add it to the array here
RegArray = ( struct data **)realloc( RegArray, ( ArrayCount + 1 ) * sizeof( struct data *) );
RegArray[ ArrayCount ] = ( struct data *)malloc( sizeof( struct data ) );

RegArray[ ArrayCount ]->Path = _strdup( CurrentPath );
RegArray[ ArrayCount ]->Key = _strdup( CurrentKey );

ArrayCount++;

有人可以告诉我这是否可以吗?如果不是,我应该如何正确操作?

谢谢!

最佳答案

您已经掌握了要点。但是,您应该进行一些改进:

  1. Don't cast the return value of malloc, realloc, calloc, etc. :

    RegArray[ ArrayCount ] = ( struct data *)malloc( sizeof( struct data ) );
    

    ...成为...

    RegArray[ ArrayCount ] = malloc( sizeof( struct data ) );
    
  2. 为防止内存泄漏,在检查是否成功后分配到预期位置之前总是realloc 到一个临时变量:

    RegArray = ( struct data **)realloc( RegArray, ( ArrayCount + 1 ) * sizeof( struct data *) );
    

    ...成为...

    struct data **tmp = realloc( RegArray, ( ArrayCount + 1 ) * sizeof( struct data *) );
    if (tmp == NULL) {
        /* handle error case */
    }
    RegArray = tmp;
    
  3. 始终检查mallocrealloccalloc等的返回值:

    RegArray[ ArrayCount ] = ( struct data *)malloc( sizeof( struct data ) );
    

    ...成为...

    RegArray[ ArrayCount ] = malloc( sizeof( struct data ) );
    if (RegArray[ ArrayCount ] == NULL) {
        /* handle error case */
    }
    
  4. 使用sizeof时使用变量而不是类型。我通常也会去掉 sizeof 中表达式周围无用的括号以提高可读性:

    RegArray[ ArrayCount ] = malloc( sizeof( struct data ) );
    

    ...成为...

    RegArray[ ArrayCount ] = malloc( sizeof **RegArray );
    

关于c - 为结构动态分配内存的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20272842/

相关文章:

c - 使用 C 读取和传输大文件

windows - postgresql 密码检查 Windows 服务器

c++ - 在 QueueUserAPC 中指定的回调未被调用

c - 如何在 C/C++ 中的 SWITCH-CASE 结构中使用 do-while 循环从头开始重新启动程序?

c++ - 我可以在 C++ 中使用 != 和 == 进行字符串比较而不用自己编写吗?

c - 通过串口将数据从 C 发送到 arduino 时,我应该进行任何转换吗?

php - Windows 2019 和 PHP 7.3 : "session_start(): ps_files_cleanup_dir: opendir failed: No such file or directory (2)"

c - C中的字符串链表

c - 正在重新分配的 int 指针未分配 C

C 在结构中释放多维数组似乎不正确