-2

Behold the following code:

#include<stdio.h>
void function ();
int main()
{
   int * a;
   *a=9;//this is supposed to give error as I am trying to 
            // dereference an unallocated pointer
           // but it does not
   printf("%d",*a);
   function();
  }
  void function()
  {
        int * a;
         *a=9;//this gives an error as I am trying to 
            // dereference an unallocated pointer
           printf("%d",*a);
           return;
     }

Output is 9 and then the program crashes... Why? The difference for main() and function() For main() we declare a pointer type then without the use of calloc or malloc is it by default allocated memory?

Abhishek Ghosh
  • 597
  • 7
  • 18

1 Answers1

4

You either got lucky with the uninitialized data, or your compiler is optimizing the pointer away.

When you do a thing like that with

int *a;
*a = 9;
printf("%d\n", *a);

The compiler can just turn that into

puts("9");

Because it can know and see all of the values.

That's probably why your function call version crashes. Because the compiler has to generate a function that can be called by other code modules.

This sort of thing will vary a lot based on compiler, compiler version, and of course the flags given to the compiler.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131