中止陷阱:6,使用memcpy复制数组

时间:2016-11-12 16:11:46

标签: c arrays malloc memcpy

我正在尝试学习如何在内存中复制一个用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。

我的问题是:

  1. 这是复制使用malloc创建的数组的最佳方法吗?
  2. Abort trap: 6是什么意思?
  3. 我只是误解了memcpy做了什么或如何使用它?
  4. 亲切的问候,

    Marcus Shepherd

1 个答案:

答案 0 :(得分:1)

变量bar没有分配给它的内存,它只是一个未初始化的指针。

你应该像之前foo

那样做
int *bar = malloc(3 * sizeof(int));

然后您需要将&地址操作符作为

删除
memcpy(bar, foo, 3 * sizeof(int));