Returning local variable and accessing uninitialized variable

bad.c

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
 
/* Function usage starts to execute. (when it gets called from main).
 * It needs some space/ memory/ world to live into.
 * It allocates its own space, where herself and everything inside her will live.
 */
const char *usage(int test)
{
    /* We declare a local array of 15 chars */
    char s[15];
     
    sprintf(s, "%d\n", test);
    
    /* We return the pointer to the local array s */
    /* gcc says: (with -Wall flag enabled)
       main.c: In function `usage':
       main.c:22: warning: function returns address of local variable
     */
    return s;
}
/* Function ended its execution, thus ended its lifetime. As a consequence, her
 * space/memory/world is no longer nescairy and it gets deallocated. As a result,
 * everything inside this world dies, except of static and dynamically allocated
 * variables (we do not have any of them here). We have a local variable in the
 * function, array s, which dies (goes out of scope).
 */

 
int main(void)
{
    int a; /* Declare a variable named a, with no initial value */
     
    /* We add 100 to a. But a has not a value. Thus we add 100 in 
       something we do not know its value and as a result, this 
       line of code means a = 100 + unknownNumber;             
       Accessing the value of an uninitialized variable yields undefined behavior 
       - it doesn't just retrieve an unknown value. But practically, the above,
       is often the case.
     */
    a += 100;
    
    /* We print where the pointer points to. The pointer is returned
       by function usage and when the function was executing, this
       pointer, names s, was pointing to a local variable(a local
       array to be exact). But the following line is equivalent to 
       this: const char* sMain = usage(a);
             printf("a is %s\n", sMain);
     sMain now, points where s was pointing to. s was pointing to
     a local variable, which went out of scope (died), when the 
     function stopped executing. Therefore, the behavior is undefined.
    */ 
    printf("a is %s\n", usage(a));
    
    return 0;
}

I would like to thank laserlight and grumpy for their precious advice.

Have questions about this code? Comments? Did you find a bug? Let me know! 😀
Page created by G. (George) Samaras (DIT)

2 thoughts on “Returning local variable and accessing uninitialized variable

  1. Pingback: How do i assign values to ponter char array????

  2. Pingback: explian hoe this funtion pointer works

Leave a comment