gpt4 book ai didi

c - memcpy 调用中的内存错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:52:57 36 4
gpt4 key购买 nike

我在调用时遇到“内存故障”:

extern void *memcpy (void *__restrict __dest,
__const void *__restrict __src, size_t __n)
__THROW __nonnull ((1, 2));

这是一段代码:

    fprintf(stderr, "sysconfig line 440 \n");
fprintf(stderr, "Value size: %d ; Pointer mymsg: %p ; Pointer value: %p ; mymsg->mtext: %s ; value: %s ; size: %d ; \n", strlen(value), mymsg, value, mymsg->mtext, value, size);
memcpy(mymsg->mtext, value, size);
fprintf(stderr, "sysconfig line 442 \n");

mymsg 是指向结构的指针:

MSG_T *mymsg;

MSG_T:

typedef struct msgInfo {
int cmd;
int arg1;
int arg2;
char mtext[MAX_SEND_SIZE];
} MSG_T;

MAX_SEND_SIZE = 4096,值是一个 (void *)char *string containing ""(\0 or empty chain) and size = 4096, 所以我不明白为什么我会遇到内存错误。我正在检查没有内存重叠。这是执行的输出:

sysconfig line 440 
Value size: 0 ; Pointer mymsg: 0x7fd49ac4 ; Pointer value: 0x7fd4ab4c ; mymsg->mtext: ; value: ; size: 4096 ;
Memory fault

我还没有发现这里有什么样的条件可以导致分段,因为所有内存都已经分配好,value 是一个空字符串,没有内存重叠。

我有时只会遇到内存错误(似乎是随机的),而其他时候进程会继续执行并退出而没有错误。

最佳答案

memcpy(mymsg->mtext, value, size);

value 是一个长度为 0 的字符串,您正试图从该字符串中复制 4096 字节。因此,您正在访问 4095 未分配的字节,这意味着您正在调用未定义的行为。

关于c - memcpy 调用中的内存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16856914/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com