Invalid read/write of size 4 in function
I'm trying to implement a function that extract some random numbers from an int array, without changing the orginal array. I wrote this function
int get_random_int(int * from, int from_length, int * result, int result_length) {
int i, pos, tmp;
int * source = malloc(sizeof(int) * from_length); // Line 720
/* Make sourcet to avoid to manipulate int array */
for (i = 0; i < from_length; i++) {
source[i] = from[i];
};
for (i = 0; i < result_length; i++) {
/* Get random pos */
pos = rand() % from_length;
/* Swap first random position with last position */
tmp = source[pos];
source[pos] = source[from_length]; // Line 732
source[from_length] = tmp; // Line 733
/* Decrease last index */
from_length--;
/* Set random value in result array */
result[i] = tmp;
};
free(source);
return 1;
}
and i call this function in main in this way
receivers = malloc(sizeof(int) * y);
get_random_int(int_arr, x, receivers, y);
// Some useful stuff
free(receivers);
int_arr is the array with int which i want to extract the values, x is the size of the array, receivers is the pointer in which i want to save random values, y his length.
The routin seems to work, but when i try to run the program using valgrind i get this error. I really not understand what is the problem
==7== Invalid read of size 4
==7== at 0x10BD30: get_random_int (main.c:732)
==7== by 0x10A5A1: main (main.c:198)
==7== Address 0x4bced08 is 0 bytes after a block of size 40 alloc'd
==7== at 0x483877F: malloc (vg_replace_malloc.c:307)
==7== by 0x10BC8F: get_random_int (main.c:720)
==7== by 0x10A5A1: main (main.c:198)
==7==
==7== Invalid write of size 4
==7== at 0x10BD4B: get_random_int (main.c:733)
==7== by 0x10A5A1: main (main.c:198)
==7== Address 0x4bced08 is 0 bytes after a block of size 40 alloc'd
==7== at 0x483877F: malloc (vg_replace_malloc.c:307)
==7== by 0x10BC8F: get_random_int (main.c:720)
==7== by 0x10A5A1: main (main.c:198)
C uses zero based arrays if you want to access the last element it's index is length-1. For example:
source[pos] = source[from_length - 1]; // Line 732
source[from_length - 1] = tmp; // Line 733