marcusshep marcusshep - 26 days ago 18
C Question

Abort trap: 6, using memcpy to copy an array

I'm trying to learn how to copy a space in memory that was allocated with malloc. I'm assuming the best way to go about this would be to use memcpy.

I am more familiar with Python. The equivalent of what I'm trying to do in Python would be:

import copy

foo = [0, 1, 2]
bar = copy.copy(foo)


Here is was I have so far.

/* 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;
}


The output of this script is as follows:

foo[0]: 0
foo[1]: 1
foo[2]: 2
Abort trap: 6


I'm compiling the script with
gcc -o foo foo.c
. I'm on a 2015 Macbook Pro.

My questions are:


  1. Is this the best way to copy an array that was created with malloc?

  2. What does
    Abort trap: 6
    mean?

  3. Am I just misunderstand what
    memcpy
    does or how to use it?



Kind regards,

Marcus Shepherd

Answer

The variable bar has no memory allocated to it, it is just an uninitialised pointer.

You should do that as you did with foo earlier

int *bar = malloc(3 * sizeof(int));

And then you need to drop the & address-of operator as

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