【问题标题】:How to reallocate memory for array of structs in C?如何为C中的结构数组重新分配内存?
【发布时间】:2025-11-25 02:50:02
【问题描述】:

我是 C 的新手。我无法正确地重新分配内存。我有一个结构数组,我必须从控制台填充它。

typedef struct net_device {
 char IPv4[16];
 char isOnline[6];
 char *name;
} net_device;

int main () {
struct net_device *net_devicies = NULL;
char *s = NULL;
int count = 0;
int length = sizeof(net_devicies)  / sizeof(net_devicies[0]);
net_devicies = malloc(sizeof * net_devicies * length++);

do {
    printf("Enter a new networ device record: Name, IPv4, isOnline\n");
    s = get_str();
    if (s) {
        char ** res  = NULL;
        char *  p    = strtok (s, " ");
        int n_spaces = 0, i;
        
        while (p) {
            res = realloc (res, sizeof (char*) * ++n_spaces);
            if (res == NULL)
                exit (-1); 
            res[n_spaces-1] = p;
            p = strtok (NULL, " ");
        }

        res = realloc (res, sizeof (char*) * (n_spaces+1));
        res[n_spaces] = 0;
        /// делаем память для имени
        net_devicies[count].name = malloc(strlen(res[0]) + 1);
        strcpy(net_devicies[count].name, res[0]);    
        strcpy(net_devicies[count].IPv4, res[1]);
        strcpy(net_devicies[count].isOnline, res[2]);            
        free(s);
        free(res);
        length++;
        net_devicies = realloc(net_devicies, sizeof(struct net_device) * length);
    }
    
} while (s);

for(int i = 0; i < 3; i++){
     printf ("name = %s; ", net_devicies[i].name);
     printf ("IPv4 = %s; ",  net_devicies[i].IPv4);
     printf ("isOnline = %s; ", net_devicies[i].isOnline);
     printf ("\n");
}
free(net_devicies);
return 0;

}

我有这个问题:

net_devicies = realloc(net_devicies, sizeof(struct net_device) * length);

输出,当我添加三个用户时:

name = Victor; IPv4 = 172.123.456.898; isOnline = false; 
name = (null); IPv4 = ; isOnline = ; 
name = (null); IPv4 =  isOnline = @Qкv; 

我只想在每次输入新字符串时增加内存。我该怎么做?

【问题讨论】:

  • sizeof(net_devicies) / sizeof(net_devicies[0]) 不会像你期望的那样工作,无论是在你分配内存之前还是之后,并且实际上使 net_devicies 指向某个地方有效。问题在于net_devicies 是一个指针,而指针(即sizeof net_devicies)的大小将是指针本身的大小,而不是它可能指向的大小。

标签: arrays c struct


【解决方案1】:

sizeof 问题可能是您的问题的原因。

在 64 位系统上,指针通常为 64 位 8 字节。 struct net_device 的大小远大于 8 个字节。

这意味着length的值将被初始化为(因为一个小的整数值除以一个大的整数值是零)。

所以

net_devicies = malloc(sizeof * net_devicies * length++);

本质上等价于

net_devicies = malloc(sizeof * net_devicies * 0);

您分配零字节!即使malloc 返回一个非空指针(你真的应该检查它!)你不能取消引用该指针。

length++改为++length即可解决,并分配一个结构。

或者更好的是使用length(在任何地方都没有++)并将length初始化为1

size_t length = 1;
net_devicies = malloc(sizeof *net_devicies * length);

你的代码还有其他问题...

例如realloc 可以失败然后返回NULL。如果发生这种情况,将不会触及已分配的内存,因此如果您重新分配作为参数传递给realloc 的同一指针,您将发生内存泄漏。使用临时变量保存realloc的结果,并检查是否为NULL

另一个问题是您总是分配了一个额外的net_device 结构,而length 会将这个可能未初始化的结构包含在数组中。

而且你不会释放你分配的所有内存,因为你没有释放net_devicies[i].name(对于任何有效索引i)。

【讨论】: