Returned string value becomes garbage

2020-05-08 07:58发布

Im trying to pass a character array value to a character pointer. then this value gets returned to a method that is calling it, but after it gets returned, the value becomes garbage. can anyone help me?

#include <stdio.h>

const char * getname(){
     char nam[10];
     char * name;
     gets(nam);
     name = nam;
     return name;
}
main(){
       printf("%s",getname());
       getch();
}

everything is fine, until the string gets returned

4条回答
Anthone
2楼-- · 2020-05-08 08:10

Your problem is that return name is returning the address of a stack variable, one that's gone out of scope after the function returns.

There are a couple of ways to fix this (at least).

The first is to have the address allocated outside of the function and then passed in:

char *getname (char *buff) {
    strcpy (buff, "pax");
    return buff;
}

char name[20];
printf ("Name is '%s'\n", getname (name));

The second is to use allocation functions that don't go out of scope on function exit (the pointers may but, as long as you pass them back, you can still get to the allocated memory):

char *getname (void) {
    char *buff = malloc (21);        // should really check this for failure.
    strcpy (buff, "pax");
    return buff;
}

buff = getname();
printf ("Name is '%s'\n", buff);
free (buff);                         // This is important, caller is responsible
                                     //   for freeing the memory.
查看更多
forever°为你锁心
3楼-- · 2020-05-08 08:14

The nam variable has function scope. This means that once the function ends, the memory for that variable is freed. So the pointer pointing to that memory that you return will not be valid any more.

You could pass in the pointer: (a bit pointless in this case, as you can see)

void getname(char *name)
{
  gets(name);
}

You could malloc (bad, because then you need to free it again at some point):

const char * getname(){
     char * name = malloc(10);
     gets(name);
     return name;
}
查看更多
叼着烟拽天下
4楼-- · 2020-05-08 08:23

Scope of nam is local to function getname(), you are returning nam address through name pointer

const char * getname(){
     char nam[10];
     :
     name = nam;
     return name;
}

allocate memory for nam; dynamically. like:

nam = malloc(sizeof(char)*10);

additionally there may be bufferoverun don't use gets(), do like:

nam = malloc(sizeof(char)*10);
fgets( nam, 10, stdin ); 

You also not need to use name an extra variable simple return nam is good.

const char * getname(){
     char * nam = malloc(sizeof(char)*10);
     fgets( nam, 10, stdin ); 
     return nam;
}
查看更多
smile是对你的礼貌
5楼-- · 2020-05-08 08:23

Declaring nam static would do also:

const char * getname() {
  static char nam[10];
  ...

Beware: This code isn't thread-safe, as nam now is treated as if it were declared globally.

查看更多
登录 后发表回答