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.
v1,v2are pointers to memory blocks that you want to operate on. But you’re passing their addresses to yourcpyarrayfunction.So you’re operating on the wrong memory blocks, stepping on memory around the
v2variable, and changing whatv2points to.