[英]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.