繁体   English   中英

如何为 C 中的结构数组重新分配 memory?

[英]How to reallocate memory for array of structs in C?

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

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);

Output,当我添加三个用户时:

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

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

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

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

这意味着length的值将被初始化为零(因为小的 integer 值除以大的 integer 值为零)。

所以

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 如果发生这种情况,已经分配的 memory 将不会被触及,因此如果您重新分配作为参数传递给realloc的同一指针,您将有 memory 泄漏。 使用临时变量来保存realloc的结果,并检查它是否是NULL

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM