我正在尝试学习如何复制内存中使用 malloc 分配的空间。我假设最好的方法是使用 memcpy。
我对 Python 比较熟悉。与我在 Python 中尝试做的事情等效的是:
import copy
foo = [0, 1, 2]
bar = copy.copy(foo)
这是我到目前为止的情况。
/* Copy a memory space
* */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
// initialize a pointer to an array of spaces in mem
int *foo = malloc(3 * sizeof(int));
int i;
// give each space a value from 0 - 2
for(i = 0; i < 3; i++)
foo[i] = i;
for(i = 0; i < 3; i++)
printf("foo[%d]: %d\n", i, foo[i]);
// here I'm trying to copy the array of elements into
// another space in mem
// ie copy foo into bar
int *bar;
memcpy(&bar, foo, 3 * sizeof(int));
for(i = 0; i < 3; i++)
printf("bar[%d]: %d\n", i, bar[i]);
return 0;
}
该脚本的输出如下:
foo[0]: 0
foo[1]: 1
foo[2]: 2
Abort trap: 6
我正在使用 gcc -o foo foo.c
编译脚本。我使用的是 2015 款 Macbook Pro。
我的问题是:
- 这是复制使用 malloc 创建的数组的最佳方式吗?
Abort trap: 6
是什么意思?- 我是否只是误解了
memcpy
的作用或如何使用它?
亲切的问候,
马库斯牧羊人
最佳答案
变量 bar
没有分配内存,它只是一个未初始化的指针。
你应该像之前对 foo
那样做
int *bar = malloc(3 * sizeof(int));
然后您需要删除 &
address-of operator as
memcpy(bar, foo, 3 * sizeof(int));
关于c - 中止陷阱 : 6, 使用 memcpy 复制数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40564848/