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.
Then, after the program is done and finished, I get a "Run-Time Check Failure #2 - Stack around the variable 'filename' was corrupted." 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. Any advice would be appreciated
Your input buffer is 10 chars long
char buffer[10];
But then you tell fgets to read up to 30 characters into the buffer
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. You might add a line
holder[r++] = '\0';
after your while-loop.
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. Or else you will face the usual problem arises due to lack of null character.
精彩评论