realloc 可以缩小左侧的数组吗(仅限 C)?
我想移动内存中的大量数据。不幸的是,这些数据被保存为数组,我无法更改它。我无法使用循环数组,因为我不想更改的几个 Fortran 方法也使用了相同的内存。最重要的是,在移动之间,数组的访问非常频繁。所以我可以这样做:
int *array = (int*) malloc(sizeof(int)*5);
int *array2=NULL;
//Now i want to move my data one step to the left
array=(int*) realloc(array,6);
array2=array+1;
memmove(array,array2,5*sizeof(int));
array=(int*) realloc(array,5);
这应该可以正常工作,但看起来很浪费;)。如果我可以告诉我的编译器删除缩小数组左侧的数据,我的数据就会在内存中蠕动,但我不必进行任何复制。像这样:
int *array = (int*) malloc(sizeof(int)*5);
//Now i want to move my data one step to the left
array=(int*) realloc(array,6);
array=(int*) realloc_using_right_part_of_the_array(array,5);
所以基本上我想以一个指向 array+1 的指针结束,并释放它左边的 4 个字节。我尝试了 free()
和 malloc()
但它不起作用...... 我知道 realloc 也可能导致 memcpy 调用,但不是每次都会!所以它可以更快,不是吗?
I want to move a large chunk of data i've got in my memory. Unfortunately this data is saved as an array, and i cannot change that. I can't use circular arrays, because the same memory is also used by a couple of fortran methods i do not want to change. On top of it, the arrays are accessed very very often in between the movement. So i can do this:
int *array = (int*) malloc(sizeof(int)*5);
int *array2=NULL;
//Now i want to move my data one step to the left
array=(int*) realloc(array,6);
array2=array+1;
memmove(array,array2,5*sizeof(int));
array=(int*) realloc(array,5);
This should work fine, but it looks so wasteful ;). If i could tell my compiler to take away data on the left side of a shrinking array, my data would sort of creep through the memory, but i wouldn't have to do any copying. Like this:
int *array = (int*) malloc(sizeof(int)*5);
//Now i want to move my data one step to the left
array=(int*) realloc(array,6);
array=(int*) realloc_using_right_part_of_the_array(array,5);
So basically i want to finish with a pointer to array+1
, with the 4 byte left of it freed. I played around with free()
and malloc()
but it didn't work...
I'm aware that the realloc could also result in a memcpy call, but not everytime! So it could be faster, couldn't it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不可以。没有办法归还您分配的内存的较低部分。另外,您的原始代码是错误的,因为您正在复制不确定的内存。
X表示不确定。
No. There is no way to give back the lower part of the memory you allocated. Also, your original code is wrong, since you're copying indeterminate memory.
X means indeterminate.
为什么不简单地把元素一一复制呢?
或者,像您一直在做的那样使用
memmove
,但不进行重定位Why don't you simply copy the elements one by one?
or, use
memmove
like you've been doing, but without the relocation