Home > Back-end >  Modifying int using a pointer
Modifying int using a pointer

Time:11-15

Why does this result in stack smashing? Is it not possible to modify the memory location using pointer?

int result;
reverseDigits2(123, &results);
printf("reverseDigits2(): %d\n", result);

void reverseDigits2(int num, int *result) {
  while (num > 0) {
    *result = num % 10;
    num /= 10;
    printf("%p %d\n", result, *result);
    result  ;
  }
}

output:

0x7ffe3ac450c4 3
0x7ffe3ac450c8 2
0x7ffe3ac450cc 1
reverseDigits3(): 3
*** stack smashing detected ***: terminated

CodePudding user response:

result will increment the memory location. If you called your function like this:

int bar;
reverseDigits2(234, &bar);

then some memory outside of the memory allocated for bar will be written, as it is shown in your output.

  •  Tags:  
  • c
  • Related