求助, 第一次发现printf调用数据后都能影响数据!!!!!
加了第一句printf的结果
# If you want to edit it correctly, please see
# Direction.txt
# CachePath
C:\Documents
# SavePath
F:\Videos
C:\Documents
F:\Videos
没加第一句printf的结果却是这样
C:\Documentsion
F:\Videosination?
这两句红色的是同一个printf函数打印出来的, 第一个与第二个差别确这么大. 拿到printf都能影响结果吗.代码在这里!!!!
- C/C++ code
void GetInfo(FILE *fp){ char str[128]; int count; for (count = 0; count < 1000; count++) { fgets(str, 128, fp); // 下面这句printf加与不加, 结果天壤之别. printf("%s\n", str); if (isspace(str[0]) || str[0] == '#') continue; else if (CachePath == NULL) { CachePath = malloc(strlen(str) * sizeof(char)); strncpy(CachePath, str, strlen(str) - 1); } else { SavePath = malloc(strlen(str) * sizeof(char)); strncpy(SavePath, str, strlen(str) - 1); break; } } //这里也有个pringf, 为什么这个printf受第一个影响. 不可思议. 我要疯了 printf("%s\n%s\n", CachePath, SavePath); fclose(fp);}[解决办法]
其实你不用加第一个printf。。。你的重点没把握好,应该在定义
char str[128];
之后memset一下
memset(str, 0, sizeof(str));
如果循环,在每次使用完后,重新使用前,都要加
memset(str, 0, sizeof(str));
不清空或者置零就有可能出现乱码
[解决办法]
按楼上说的清零下buffer,而且malloc的内存没有释放?
[解决办法]
[解决办法]
嗯,上面说的对,我失误了,应该是CachePath和SavePath申请了内存之后要置零,还有,就是说感觉楼主malloc的长度太短啊。。。应该是strlen(str) + 1吧,strncpy的时候也不应该-1啊,除非最后一位不要了,因为strlen是不包含最后那个结束符'\0'的
[解决办法]
memcpy、strncpy、strlen之类的后边都要有结束符的