[英]strcpy() in c gives me 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;
指針struct clients* first;
不指向任何malloc
d 內存,因此嘗試訪問其上的屬性,例如first->client_id = 1
是未初始化的指針取消引用。
由於取消引用后行為未定義,分段錯誤可能發生在strcpy
(或其他任何地方,但strcpy
不是罪魁禍首)。 考慮使用valgrind 之類的工具在發生這些非法內存訪問時識別它們。
還,
線路:
first->name = NULL; memset(&first->name, 0, sizeof(first->name));
不要真正做任何事情,因為first->name
內存位置隨后被覆蓋。 你可以省略這些。
(char*)malloc(100*sizeof(char));
可以只是malloc(5)
。 sizeof(char)
保證為 1 個字節, (char *)
是不必要的強制轉換,而100
對於"User"
是太多內存,它只需要 5 個字符(一個用於空終止符)。
free
分配的內存以避免泄漏。
檢查malloc
的返回值以確保成功分配內存是一個好主意。
您可以使用strdup
代替malloc
/ strcpy
對,但這樣做的缺點是您可能會忘記strdup
分配的需要釋放的內存。
這是重寫(省略了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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.