Memcpy segfault with large arrays

I have a function that swaps 2d arrays in C using memcpy. I know that you can change pointers, but I would like to make a comparison between copying arrays and exchange pointers.

Here is my code for it, 2d arrays are nx n.

void swap_arrays(int n, float old[][n], float new_arr[][n]) {
    float temp[n][n];
    int arr_size = sizeof(float) * n * n;
    memcpy(temp, old, arr_size);
    memcpy(old, new_arr, arr_size);
    memcpy(new_arr, temp, arr_size);
}

It works fine for a 5 x 5 array, but it shrinks significantly when the array is larger (the actual size I need is 4000+, it starts crashing at 2000+), on the first memcpy. Any help is appreciated.

+4
source share
3 answers

It disconnects from 4000, but not with an error memcpy(). This is because the size exceeds the stack size of your program.

, , -

float *temp;
temp = malloc(sizeof(float) * n * n);
if (temp != NULL)
{
    /* memcpys here */
}

, , , , -

float **temp;
temp = malloc(sizeof(float *) * n);
for (size_t i = 0 ; i < n ; ++i)
    temp[i] = malloc(sizeof(float) * n); /* please check for `NULL' */

free() , memcpy() , . temp , float, , memcpy().

+6

, - , temp, . memcpying :

void swap_arrays(int n, float old[n][n], float new[n][n])
{
    size_t sz = sizeof(float[n][n]);
    void *buf = malloc(sz);
    if ( !buf ) exit(EXIT_FAILURE);

    memcpy(buf, old, sz);
    memcpy(old, new, sz);
    memcpy(new, buf, sz);

    free(buf);
}

, , float a[n][n]; . , malloc, :

float (*a)[n] = malloc(n * sizeof *a);
float (*b)[n] = malloc(n * sizeof *b);

, "" , : void *tmp = a; a = b; b = tmp;

+3

. @iharod , . , , .

Linux:

alan@~$ulimit -all
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 62978
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 62978
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

, 8192k .

ulimit , :

alan@~$ulimit -s <stack_size_you_want>.

, .

0

Source: https://habr.com/ru/post/1606334/


All Articles