![](/img/trans.png)
[英]C++: how to reallocate array using same memory space but going down in size
[英]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.