[英]Buffer Overflow when using strcpy function
I'm trying to use strcpy in order to put a string in an array of strings. 我正在尝试使用strcpy以便将字符串放入字符串数组中。 This is my definiton of the arrays:
这是我对数组的定义:
char movies[10][150], movie[150];
int i = 0, j = 0;
currentChar = getchar();
while(currentChar != EOF)
{
while(currentChar!='\n')
{
movie[i] = currentChar;
currentChar = getchar();
i++;
}
strcpy(*(movies + j*10*15), (char*)movie);
j++;
currentChar = getchar();
}
Trying to debug it in c++ console, I get a 'Buffer is too small' message. 尝试在c ++控制台中对其进行调试时,收到“缓冲区太小”消息。
note: My input is "Django unshaved:a bit bloody, but overall a solid film" which does not exceed the 150 chars. 注意:我的输入是“不剃Django:有点血腥,但总体来说很坚固”,不超过150个字符。
thanks for helping. 感谢您的帮助。
edit: code edited to show full picture 编辑:已编辑代码以显示全图
You should use this code instead: 您应该改用以下代码:
strcpy(movies[j], movie);
IMHO, it doesn't make sense to define a two-dimensional array and then use it as if it was one large one-dimensional array defined as char[1500]. 恕我直言,先定义一个二维数组然后再使用它就像将其定义为char [1500]一样是一个大的一维数组是没有意义的。
Also, which compiler are you using that generates such a message for C
-code? 另外,您正在使用哪个编译器为
C
代码生成这样的消息?
您的复制函数调用应为:
strcpy((movies + j*150), (char*)movie);
Finally I solved the problem. 最后我解决了这个问题。 Apparently, in the end of 'movie' there wasn't a '\\n' character and strcpy could not handle it.
显然,在“电影”结尾没有一个“ \\ n”字符,而strcpy无法处理它。
Adding a '\\n' at the end of the string solves the problem. 在字符串末尾添加“ \\ n”可以解决该问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.