The code below is supposed to create two 2D arrays (posa and posb) that have contiguous memory locations, and then copy posa over posb using memmove function. Surprisingly, it works well for "small" array sizes (e.g.: size1=size2=100), but I get a segmentation fault (core dump) for larger sizes (e.g.: size1=size2=300). As I am using dynamic memory allocation, I presume this is not a stack overflow issue like here... Can somebody explain what I'm doing wrong ?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int ** Allocation_array_x2(int size1, int size2){
int **ptr;
int i;
ptr = malloc(size1 * sizeof(*ptr));
if(ptr == NULL) {
fprintf(stderr,"Allocation error");
exit(1);
}
ptr[0] = malloc(size1 * size2 * sizeof(**ptr));
for(i=1 ; i < size1 ; i++){
ptr[i]=ptr[0]+(i * size2);
if( ptr[i] == NULL) {
fprintf(stderr,"Allocation error");
exit(1);
}
}
return ptr;
}
void Free_array_x2(int **ptr){
free(ptr);
ptr=NULL;
}
int main(){
int size1=300, size2=300;
int **posa, **posb;
posa=Allocation_array_x2(size1,size2);
posb=Allocation_array_x2(size1,size2);
/* array_filling */
for( int j = 0 ; j<size1 ; j++ ) {
for( int k = 0 ; k<size2 ; k++ ) {
posa[j][k] = 2*j+3*k+1;
posb[j][k] = 1000;
}
}
memmove(posb,posa,size1*size2*sizeof(int));
for(int i = 0 ; i<size1 ; i++ ) {
for(int j = 0 ; j<size2 ; j++ ) {
printf("%d\t%d\n",posa[i][j],posb[i][j]);
}
}
Free_array_x2(posa);
Free_array_x2(posb);
}