0

I have a question for you. I was reading some information about pointer in c and memory allocation, and I saw a little program which create an error when it runs:

#include <stdio.h>

char* getname(void){
    char nstring[25];
    printf("Please type your name");
    gets(nstring);
    putchar('\n')
    return nstring; //Serious error in this program
}

int main(void){
    char* myname;
    myname = getname();
    printf("%n\n", myname);
    return 0;
}

Why is there a comment in the code that says "Serious error in this program" ? I do not understand where the error is happening. Can someone explain it to me ?

Irf
  • 4,285
  • 3
  • 36
  • 49
  • 1
    Undefined behavior for accessing an object after its lifetime has ended. Undefined behavior for using the value of a pointer after the lifetime of the object it points to has ended. – EOF Dec 20 '16 at 17:54
  • 2
    Never ever use `gets`. It is dangerous and will sooner or later lead to bad things happening. It has also been deprecated since the C99 standard, and removed completely in the C11 standard. Use [`fgets`](http://en.cppreference.com/w/c/io/fgets) instead. – Some programmer dude Dec 20 '16 at 17:55

1 Answers1

1

Why is there a comment in the code that says "Serious error in this program" ?

Because you are returning a local string char nstring[25]; whose scope and life are limited to that particular function which is undefined behavior

Raghu Srikanth Reddy
  • 2,703
  • 33
  • 29
  • 42