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

标签 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 的作用或如何使用它?

亲切的问候,

马库斯牧羊人

最佳答案

变量 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/

相关文章:

c - 这个程序怎么可能有意义?

c++ - 在字符串中移动一个单词,单词之间用空格作为分隔符

c - 用C中的空格替换字符数组中的制表符

c - 通过数组的最有效方法?

c - C中未知数量字符串的文件IO

c - c 中 malloc() 和 free() 的正确使用

c - 保留函数体中分配的内存

java - 如何将一个字符串分成多个部分?

javascript - 使用 jQuery 在 javascript 中迭代关联数组(键/值对),其中值是 jQuery 对象

linux - "linux process address space"是如何存储的?