[英]Strange errors with Visual C++
Alright, this is my code so far 好了,这是我到目前为止的代码
int main()
{
char buffer[10];
int arraySize = -1;
FILE *fp;
int i;
char filename[10];
int userNo = 1;
char stockArray[18][15];
sprintf(filename, "file%d", userNo);
fp = fopen(filename, "r");
while(fgets(buffer, 30, fp) != NULL)
{
if(buffer[0] == '<' && buffer[1] == 's')
{
arraySize++;
}
else if(buffer[0] == '<' && buffer[1] == '/'){printf("< char\n");}
else
{
int t = 0;
int r = 0;
while(buffer[t] != '>')
{
t++;
}
t++;
char holder[15] = {'\0'};
while(buffer[t] != '<')
{
holder[r] = buffer[t];
t++;
r++;
}
strncpy(stockArray[arraySize], holder, r);
printf("%s\n", stockArray[arraySize]);
}
}
fclose(fp);
}
I'm running into two strange issues. 我遇到两个奇怪的问题。 First, when I do the printf statement, it prints the proper data just fine, then does the following: if the first word is "banana" and the next is "123" it prints "123ana" and then a bunch of weird character that ends with, I kid you not, a smiley face.
首先,当我执行printf语句时,它会打印正确的数据,然后执行以下操作:如果第一个单词是“ banana”,下一个单词是“ 123”,则它会打印“ 123ana”,然后输出一堆奇怪的字符最后,我不骗你一张笑脸。
Then, after the program is done and finished, I get a "Run-Time Check Failure #2 - Stack around the variable 'filename' was corrupted." 然后,在程序完成并完成后,出现“运行时检查失败#2-变量'filename'周围的堆栈已损坏”。 error.
错误。
I'm using VS2010 and C++, and all my experience thus far has been with GCC and C, where I've never encountered these problems before. 我正在使用VS2010和C ++,到目前为止,我的所有经验都是在GCC和C上进行的,而我以前从未遇到过这些问题。 Any advice would be appreciated
任何意见,将不胜感激
Your input buffer is 10 chars long 您的输入缓冲区长10个字符
char buffer[10];
But then you tell fgets to read up to 30 characters into the buffer 但是然后您告诉fgets最多将30个字符读入缓冲区
fgets(buffer, 30, fp)
That is likely to have "funny" effects! 那可能会产生“滑稽”的效果!
One thing I recognized on visual inspection is that your holder
is not properly null-terminated. 我在外观检查中认识到的一件事是,您的
holder
未正确以零结尾。 You might add a line 您可以添加一行
holder[r++] = '\0';
after your while-loop. 在您的while循环之后。
Its very difficult to point out the problem, without understanding what exactly you're doing, and what the file contains. 在不了解您到底在做什么以及文件包含什么的情况下很难指出问题。
But I still suggest one thing and try: 但我仍然建议一件事并尝试:
strncpy(stockArray[arraySize], holder, r);
stockArray[arraySize][r] = '\0'; //do this before printf!
In general, make sure all your c-strings are null-terminated. 通常,请确保您所有的c字符串都为空终止。 Or else you will face the usual problem arises due to lack of null character.
否则您将面临由于缺少空字符而引起的常见问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.