The following code gives me a terminated by signal SIGSEGV (Address boundary error):
void rec(int x, int *arr, int *size) {
if (x < 0) {
rec(-x, arr, size);
return;
}
arr = realloc(arr, sizeof(int) * ++(*size));
*(arr + (*size) - 1) = x % 10;
if (x % 10 != x)
rec(x / 10, arr, size);
}
int main() {
int *arr = malloc(sizeof(int));
int *size = malloc(sizeof(int));
*size = 0;
rec(20, arr, 0);
}
I already figured our that the arr counter in the main method won't hold the desired result, but I still can't understand why I'm getting an error.
Notice that you are passing NULL as third argument:
rec(20, arr, 0); // 0 is NULL
and you get a segfault dereferencing it:
arr = realloc(arr, sizeof(int) * ++(*size)); // here size is `NULL`
try with
rec(20, arr, size);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With