[英]C - Dynamic Memory allocation - copy string
for the following program 对于以下程序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int size = 16, len = 0, c;
char* data = (char*)malloc(sizeof(char) * size);
while((c = getchar()) != EOF) {
if(len == size) {
size *= 2;
char* data_new = (char*)realloc(data, sizeof(char) * size);
if(data_new == NULL) {
free(data);
return -1;
}
if(data_new != data) {
memcpy(data_new, data, size);
data = data_new;
}
}
data[len] = c;
len++;
}
data[len] = '0';
printf("%s\n", data);
free(data);
return 0;
}
I think the error lies in the realloc part because if im setting the size int high everything works fine. 我认为错误在于realloc部分,因为如果im将size设置为int high,则一切正常。
Does someone have a tip for me how i can do this realloc thing correctly? 有人给我一个提示,我如何正确地重新分配呢?
thx for your support 感谢您的支持
You don't need to copy the data when realloc
returns a different pointer - that is done for you. 当
realloc
返回不同的指针时,您不需要复制数据-为您完成。 In fact it is a mistake because you are copying the data from a source that no longer exists, and twice the quantity that it had! 实际上,这是一个错误,因为您正在从不再存在的源中复制数据,并且复制的数据量是原来的两倍! So you only need
所以你只需要
data = data_new;
Also this line is wrong 另外这条线是错误的
data[len] = '0';
it should be 它应该是
data[len] = '\0';
and can also write beyond the memory bounds. 并且还可以写超出内存范围的内容。 You should be checking the size again before writing the terminator, or more simply, reallocate the memory when
size-1
has been used, because you know you'll be needing that extra byte. 您应该在写入终止符之前再次检查大小,或更简单地说,在使用
size-1
时重新分配内存,因为您知道将需要该额外的字节。
if(len == size - 1) {
// . . .
}
Note too that if you are entering characters each separated by a newline then getchar()
will read every newline too. 还要注意,如果要输入每个换行符分隔的字符,则
getchar()
也会读取每个换行符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.