user1478167
user1478167

Reputation: 75

Buffer overflow wrong variable changing value

#include <stdio.h>
#include <stdlib.h>

int test(void)
{
  int a=0,b=0;
  char buf[4];
  gets(buf);
  printf("a:%d b:%d",a,b);
}

int main()
{
  test();
  return 0;
}

Question is why with input:aaaaa a is becoming 97 instead of b?From the way variables are declared inside test when buf overflows shouldn't it affect first b and then a?

Upvotes: 0

Views: 827

Answers (2)

Cacho Santa
Cacho Santa

Reputation: 6914

a and b variables will not be necessarily contiguous to the variable buf. Consequently, the overflow of the variable buf, has nothing to do with the possible values of a and b. The behaviour will be undefined.

However, it is important to mention that the C standard will store all of the arrays, such as buf, in continuous memory location.

Here you can check the documentation:

An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.

Upvotes: 1

Nigel Harper
Nigel Harper

Reputation: 1250

Undefined behaviour is undefined. There's nothing in the language standard about the relative locations of different variables in a function, and there's definitely no guarantees about what will happen in a buffer overflow situation.

Upvotes: 0

Related Questions