c中的char指针

noM*_*MAD 2 c string pointers

我是C编程的新手,我无法弄清楚为什么会这样.

char *example(char *temp) {
      char *xyz;
      memset(xyz,0,strlen(temp));
      strncpy(xyz,temp,3);
      strcat(xyz,"XX);
      return xyz;
      }

int main() {
      char temp[] = "ABCDEF"
      char *xyz;
      xyz = example(temp);
      printf("Returned string is: %s",xyz);
      return 0;
      }
Run Code Online (Sandbox Code Playgroud)

我只是想知道所有我做错了,因为我试图运行GDB而事实证明,我试图访问的内存有些不可达的一部分,但我无法弄清楚.提前致谢.

Mys*_*ial 6

问题出在这里:

char *xyz;
memset(xyz,0,strlen(temp));
Run Code Online (Sandbox Code Playgroud)

你从未初始化xyz.因此它是一个无效的指针.

你需要做什么为它分配一些东西:

char *xyz = malloc(strlen(temp) + 1);   //  Allocate, +1 is for the '\0'.
memset(xyz,0,strlen(temp));
Run Code Online (Sandbox Code Playgroud)

当你完成它时释放它:

int main() {
    char temp[] = "ABCDEF"
    char *xyz;
    xyz = example(temp);
    printf("Returned string is: %s",xyz);

    free(xyz);   //  Free

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编辑:其他问题:

这三条线路非常危险:

  memset(xyz,0,strlen(temp));
  strncpy(xyz,temp,3);   //  The nul is not copied in strncpy.
  xyz[3] = '\0';         //  Add the nul manually.
  strcat(xyz,"XX");      //  You need to ensure that xyz is large enough.
Run Code Online (Sandbox Code Playgroud)