/* * Test program to consider what happens to local variables after the * function has completed. * * Brian D. Davison * * Last revised 5 Feb 2005 */ #include #include // Yes we are intentionally returning address of local variable int *func1(void) { int a = 3; return &a; } // Yes we are intentionally returning address of local variable int *func2(void) { int b = 4; return &b; } int *func3(void) { int *f1 = NULL; int *f2 = NULL; f1 = func1(); // record first result f2 = func2(); // record second result return f1; // send back first result } // This function doesn't actually do anything useful. int usefloat(void) { float g=422.3; g *= 71; return (int) g/100; } int *func4(void) { int *f1 = NULL; int x; f1 = func1(); // record first result x = usefloat(); // some other kind of function return f1; // send back first result } int main(int argc, char *argv[]) { int choice = 0; int *result = NULL; if (argc != 2) { printf("Expects one argument: which function to run.\n"); exit(-1); } choice = atoi(argv[1]); switch(choice) { case 1: printf("Expected result is 3.\n"); result = func1(); break; case 2: printf("Expected result is 4.\n"); result = func2(); break; case 3: printf("Expected result is 3.\n"); result = func3(); break; case 4: printf("Expected result is 3.\n"); result = func4(); break; default: printf("Invalid argument.\n"); return (0); } printf("Actual result was %d\n", *result); return 0; }