c 中的 strcpy() 给了我分段错误

NNN*_*NNN 1 c segmentation-fault

我正在尝试将名称分配给 TCP 服务器中的客户端,但该strcpy()功能给了我一个分段错误。

struct clients{
  int client_fd;
  char* name;
  struct clients* next;
}

struct clients* first;
first->client_fd = 1;
first->name = NULL;
memset(&first->name, 0, sizeof(first->name));
first->name = (char*)malloc(100*sizeof(char));
strcpy(first->name, "User");
first->next = NULL;
Run Code Online (Sandbox Code Playgroud)

ggo*_*len 5

指针struct clients* first;不指向任何mallocd 内存,因此尝试访问其上的属性就像first->client_id = 1是未初始化的指针取消引用。

因为在取消引用后行为未定义,分段错误可能发生在strcpy(或其他任何地方,但strcpy不是罪魁祸首)。考虑使用valgrind 之类的工具在发生这些非法内存访问时识别它们。

还,

  • 线路:

      first->name = NULL;
      memset(&first->name, 0, sizeof(first->name));
    
    Run Code Online (Sandbox Code Playgroud)

    不要真正做任何事情,因为first->name内存位置随后被覆盖。你可以省略这些。

  • (char*)malloc(100*sizeof(char));可以只是malloc(5)sizeof(char)保证为 1 个字节,(char *)是不必要的强制转换,并且100对于 来说太多内存"User",只需要 5 个字符(一个用于空终止符)。

  • free 分配的内存以避免泄漏。

  • 检查malloc的返回值以确保成功分配内存是一个好主意。

  • 您可以使用/对strdup代替,但这样做的缺点是您可能会忘记需要释放的已分配内存。mallocstrcpystrdup

这是重写(malloc省略返回检查):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct clients {
    int client_fd;
    char* name;
    struct clients* next;
};

int main(void) {
    struct clients* first = malloc(sizeof(*first));
    first->client_fd = 1;
    first->name = malloc(5);
    strcpy(first->name, "User");
    first->next = NULL;

    printf("%d %s\n", first->client_fd, first->name); // => 1 User

    free(first->name);
    free(first);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)