user1607425
user1607425

Reputation:

Segmentation fault when printing copy of array

The following program segfaults when v2 is printed but not during the array copy. Does anyone know why?

#include <stdio.h>
#include <stdlib.h>

void cpyarray (void* dst, void* src, size_t memsize, size_t size) {

    for (size_t i = 0; i < size; i++) {

        *(((char*) dst) + i*memsize) = *(((char*) src) + i*memsize);
    }
}

int main () {

    size_t N = 10;

    double* v1 = (double *) malloc(N * sizeof(double));
    double* v2 = (double *) malloc(N * sizeof(double));

    for (size_t i = 0; i < N; i++) *(v1+i) = i;

    printf("\n\nv1: ");
    for (size_t i = 0; i < N; i++) printf("%g ", v1[i]);

    cpyarray(&v2, &v1, sizeof(double), N);

    printf("\n\nv2: ");
    for (size_t i = 0; i < N; i++) printf("%g ", v2[i]); // program crashes here

    return 0;
}

EDIT: the code does not crash if I copy arrays of ints instead of doubles.

Upvotes: 0

Views: 451

Answers (4)

Pete Becker
Pete Becker

Reputation: 76245

In addition to the problem that the current answers have pointed out, cpyarray doesn't copy the array, just some parts of it. Instead of trying to imitate types with i*memsize, just treat the memory block as a bunch of bytes and copy them one by one. Now all you have to do is figure out how many bytes to copy, which isn't hard.

Upvotes: 0

Miroslav Bajtoš
Miroslav Bajtoš

Reputation: 10785

You are passing wrong pointers to cpyarray function.

Your code sends pointer to array (pointer to pointer to double)

cpyarray(&v2, &v1, sizeof(double), N);

You should send array instead (pointer to double)

cpyarray(v2, v1, sizeof(double), N);

Upvotes: 0

pb2q
pb2q

Reputation: 59607

v1, v2 are pointers to memory blocks that you want to operate on. But you're passing their addresses to your cpyarray function.

So you're operating on the wrong memory blocks, stepping on memory around the v2 variable, and changing what v2 points to.

cpyarray(v2, v1, sizeof(double), N);

Upvotes: 2

chrisaycock
chrisaycock

Reputation: 37930

You are passing &v2 to cpyarray(), which means that your function is changing where v2 is pointing! Since it's now pointing to an invalid location, you get a seg fault when you dereference it for printf().

Instead, just pass v2 to cpyarray().

Upvotes: 0

Related Questions