c - C 中增长内存中的多维数组

标签 c memory struct malloc realloc

这是我的代码:

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

typedef struct{
char ipaddr[20];
char filename[2048];
}iplog;

int main(){
    unsigned long numrec=0;
    iplog* e=(iplog*)calloc(1,sizeof(iplog)+1);
    iplog* p=e;
    memcpy(e->ipaddr,"127.0.0.1",20);
    memcpy(e->filename,"/bla/bla/bla",2048);
    e=(iplog*)realloc(e,sizeof(iplog)*(numrec++)+1); //memory not growing?
    e++;
    memcpy(e->ipaddr,"192.168.1.2",20);
    memcpy(e->filename,"/abc/def/ghi",2048);
    for (*p;p;p++){
        printf("IP=%s, File=%s\n",p->ipaddr,p->filename);
    }
    free(e);
    return 0;
}

我想做的是在 RAM 中创建一个结构数组。我无法使用格式 array[n].element=value 因为我不知道需要多少内存来处理所有元素,所以我认为每次都重新分配内存的好处。当我引入 realloc 时,就会发生段错误。

这是我的逻辑并纠正我犯的错误。首先,我分配足够的内存(通过 sizeof(iplog)) 加上一个字节用于空字符。然后我将数据发送到结构的每个元素。没有问题。

我将原始分配的内存访问指针用于内部 realloc,因此我不会使用自己的指针分配数百个新的内存块。第二个参数的值有足够的空间来包含我需要的所有结构数据。我使用 numrec++ 来实现这一点。

然后,我增加数据指针(通过 e++)以将数据写入内存中的新空间。

最后,我使用第一次分配内存的原始指针来尝试迭代内存中的数据来打印它,我在输出中看到的只是打印的行数不正确以及段错误如下:

IP=, File=
IP=, File=
...
...
IP=, File=
IP=, File=
Segmentation fault

我对上面代码的期望是这样的:

IP=127.0.0.1, File=/bla/bla/bla
IP=192.168.1.2, File=/abc/def/ghi

我做错了什么?我假设它与 realloc 有关?

最佳答案

线路

e=(iplog*)realloc(e,sizeof(iplog)*(numrec++)+1);

相当于:

e=(iplog*)realloc(e,sizeof(iplog)*(numrec)+1);
numrec = numrec + 1;

由于 numrec 已初始化为 0,因此您实际上使用:

e=(iplog*)realloc(e,1);

这解释了段错误的问题。

将该行更改为:

// You need to be able hold 2 iplog objects.
numrec = 1;
e = realloc(e,sizeof(iplog)*(++numrec)); // No need of the extra +1
                                         // No need of the explicit cast either.

关于c - C 中增长内存中的多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33029147/

相关文章:

c - '->' doesnt doesn' t 适用于结构内部的结构

c++ - Linux内存管理开销

c - C错误中的LinkedList

c - 无法在 mergeSort 函数中释放内存

ruby-on-rails - 如何在 Rails 中以 mb 为单位获取 ruby​​ 对象的大小?

c - 给指针赋值?

c# - 为什么 C# 对内部 KeyValuePairs 使用结构而不是类

c - 如何发送信号?

c - 如何正确测量CUDA时间?

c++ - 移动窗口并调整底部闪烁的大小