c-初始化结构后,strcpy中为什么出现分段错误



我似乎不明白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("Hellon");
}

EDIT:CCD_ 2假定为CCD_"报价

编辑:谢谢你的评论!这已经通过malloc'ing消息->缓冲区为buf:腾出空间

message_t messageA = {"", 130};
message_t *message = &messageA;
message->buffer = malloc(122);
strcpy(message->buffer, buf);
printf("Hellon");

这里需要注意的几点。

当您声明存储数据的指针时,您可以直接在声明处分配(通常用于小字符串而不是大字符串(,也可以使用动态内存分配函数

#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  character
message->buffer = malloc( strlen(buf) + 1 );
// check allocated memory is success or not
if ( message->buffer )
{
strcpy(message->buffer, buf);
printf("buffer = %sn",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 failedn");
}
printf("Hellon");
return 0;
}
message_t messageA = {"", 130};

在这里,您正在初始化messageA.buffer = ""。它是一个字符串文字。所以,你不能修改存储在其中的字符串。如果你试图修改它,你会得到分段错误。

message_t *message = &messageA;
strcpy(message->buffer, buf);

在这里,您正在修改字符串文字message->buffer。这就是为什么你有分割错误
请访问此问题修改字符串文字

尝试使用message->buffer = strdup(buf);为您进行mallocstrlen计算。

相关内容

  • 没有找到相关文章

最新更新