[英]Why is there a segmentation fault in strcpy after initializing a struct?
我似乎無法弄清楚為什么strcpy
在這段代碼中會出現分段錯誤。 它應該很簡單:
typedef struct message {
char *buffer;
int length;
} message_t;
int main () {
char* buf = "The use of COBOL cripples the mind; its "
"teaching should, therefore, be regarded as a criminal "
"offense. -- Edsgar Dijkstra";
message_t messageA = {"", 130};
message_t *message = &messageA;
strcpy(message->buffer, "buf");
printf("Hello\n");
}
編輯: strcpy(message->buffer, "buf")
應該是strcpy(message->buffer, buf)
沒有 "" 引號
編輯:感謝您的評論:這已通過 malloc'ing message->buffer 為 buf 騰出空間來解決:
message_t messageA = {"", 130};
message_t *message = &messageA;
message->buffer = malloc(122);
strcpy(message->buffer, buf);
printf("Hello\n");
這里有幾點需要注意。
當您聲明存儲數據的指針時,您可以直接在聲明中分配(通常用於小字符串而不是大字符串),或者您應該使用動態 memory 分配函數分配 memory
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct message {
char *buffer;
int length;
} message_t;
int main () {
char* buf = "The use of COBOL cripples the mind; its "
"teaching should, therefore, be regarded as a criminal "
"offense. -- Edsgar Dijkstra";
message_t messageA = {"", 130};
message_t *message = &messageA;
//allocate memory to buffer length of buf, + 1 for \0 character
message->buffer = malloc( strlen(buf) + 1 );
// check allocated memory is success or not
if ( message->buffer )
{
strcpy(message->buffer, buf);
printf("buffer = %s\n",message->buffer );
//free the malloc'ed memory to avoid memory leaks
free(message->buffer);
//make the pointer NULL, to avoid dangling pointer
message->buffer = NULL;
}
else
{
printf("malloc failed\n");
}
printf("Hello\n");
return 0;
}
message_t messageA = {"", 130};
在這里,您初始化messageA.buffer = ""
。 它是一個字符串文字。 因此,您不能修改存儲在其中的字符串。 如果你試圖修改它,你會得到分段錯誤。
message_t *message = &messageA;
strcpy(message->buffer, buf);
在這里,您正在修改字符串文字message->buffer
。 這就是您遇到分段錯誤的原因。
請訪問此問題Modifying a string literal
嘗試使用message->buffer = strdup(buf)
; 為您執行malloc
和strlen
計算。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.