0
void swap (int *px, int *py) {
int temp;
temp = *px;
*px = *py;
*py = temp;
}

that will swap two variables, which looks okay for me.

now if I change it to

void swap (int *px, int *py) {
int *temp;
*temp = *px;
*px = *py;
*py = *temp;
}

notice int *temp

this works anyway though, but temp is dereferenced without being initialized.

what value would this not work for?

like if i want to make a method called proc how could i gurantee the program will crash? I think I am supposed to leave something on the stack.

int main () {
int a = 1, b = 2;
proc(/* Some args might go here */);
swap(&a, &b);
}
Serg
  • 2,140
  • 1
  • 12
  • 14
user2054534
  • 181
  • 3
  • 5
  • 17
  • This brings up undefined behavior for all I know. Dereferencing and writing to NULL would've guarenteed a crash I believe. – user123 Mar 18 '13 at 20:35
  • @Magtheridon96 It is also UB: http://stackoverflow.com/questions/2727834/c-standard-dereferencing-null-pointer-to-get-a-reference – Andreas Fester Mar 19 '13 at 10:14
  • possible duplicate of [Uninitialized pointers in code](http://stackoverflow.com/questions/5870038/uninitialized-pointers-in-code) – ecatmur Mar 19 '13 at 10:48

2 Answers2

1

Since int is a base type, why not just...

void swap (int *px, int *py) { int temp; temp = *px; *px = *py; *py = temp; }

Anonymouse
  • 935
  • 9
  • 20
0

What you do is relying on good luck: the uninitialized int *temp; uses some garbage from the stack and if you lucky enough, it's dereference will crash the program with SIGSEGV (AccessViolation on Windows), otherwise (and it's much worse!) it spoils some existing memory location's data which may crucial for the program, but it will show up much later as a mysterious geizenbug.

So the behavior of an uninitialized pointer completely depends on the state of the stack, which is virtually random: depending on what functions have been called before and what amount of data they used and their local variables.

Dmytro Sirenko
  • 5,003
  • 21
  • 26