[valgrind message]
==16958== 1 errors in context 1 of 2:
==16958== Invalid read of size 4
==16958== at 0x109637: arr_del (in /home/students/s/smelov.vp/lab3/lab3)
==16958== by 0x10939D: main (in /home/students/s/smelov.vp/lab3/lab3)
==16958== Address 0x4a19938 is 0 bytes after a block of size 24 alloc'd
==16958== at 0x483E7CF: realloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==16958== by 0x109541: arr_corr (in /home/students/s/smelov.vp/lab3/lab3)
==16958== by 0x109323: main (in /home/students/s/smelov.vp/lab3/lab3)
[functions code]
int main(){
int input=0;
int *arr;
int s;
size_t index;
scanf("%d", &input);
switch(input){
case 2:
scanf("%zu", &index);
arr = arr_corr(arr, index, &s);
arr_output(arr, s);
break;
case 3:
scanf("%zu", &index);
arr = arr_del(arr, index, &s);
arr_output(arr, s);
break;
}
}
int* arr_corr(int *arr, size_t index, int *s){
int n;
(*s) = (*s) 1;
arr = (int*) realloc(arr, (size_t)(*s) * sizeof(int));
for(size_t i = (size_t)((*s)-1); i>=index; i--){
arr[i 1] = arr[i];
}
scanf("%d", &n);
arr[index]= n;
return arr;
}
int* arr_del(int *arr, size_t index, int *s){
for(size_t i=index; i<(size_t)(*s); i ){
arr[i]=arr[i 1];
}
(*s)=(*s)-1;
arr = (int*) realloc (arr, (size_t)(*s) * sizeof(int));
return arr;
}
I just don't understand what this message means and what I did wrong. Pls help me! Everything I know is that there is no problem with main() function and with anything else. The code is located in two files. There is also no problem with linking these files.
CodePudding user response:
==16958== Address 0x4a19938 is 0 bytes after a block of size 24 alloc'd
==16958== at 0x483E7CF: realloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
You realloc'd something of size 24 bytes (6 int
s).
==16958== Invalid read of size 4
==16958== at 0x109637: arr_del (in /home/students/s/smelov.vp/lab3/lab3)
You tried to read beyond the end of that memory (bytes 25 to 27, or the int array at index 6).
It would be clearer if you compiler your code with debug information (-g).
To fix this you either need to allocate more memory or do something like change your loop control so that you stop sooner and don't read too far.