Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting address boundary error when working with pointers in C

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.

like image 966
Hilberto1 Avatar asked Apr 01 '26 05:04

Hilberto1


1 Answers

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);
like image 77
David Ranieri Avatar answered Apr 08 '26 17:04

David Ranieri