使用memcpy编译目标对象中的缓冲区溢出的编译器警告/错误

时间:2019-04-11 17:55:27

标签: c

使用memcopy将数据从const字符串复制到数组-(->是结构的成员)时,编译器将抛出错误,导致目标对象中的缓冲区溢出

感谢您的学习。

#define LEN 9
typedef struct buff_ {
....
..
char bowl[LEN];
}buff;
buff *dest= NULL;
dest= malloc......();// This is allocated properly
'
'
'
memcpy(dest->bowl,"y",LEN); //compiler throwing error here:buffer overflow


将字符串复制到LEN大于src的buffer(dest)中应该不会有任何错误。

1 个答案:

答案 0 :(得分:2)

尝试使用,这将限制为LEN或字符串的实际长度,以较小者为准:

strncpy(dest->bowl,"y",LEN);