问题描述
我不明白为什么我在运行此程序时将过多的空白写入stdout。
$ valgrind ./bin/speller texts/lalaland.txt > test/lalaland.txt
==28984== Memcheck,a memory error detector
==28984== copyright (C) 2002-2017,and GNU GPL'd,by Julian Seward et al.
==28984== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==28984== Command: ./bin/speller texts/lalaland.txt
==28984==
==28984==
==28984== HEAP SUMMARY:
==28984== in use at exit: 0 bytes in 0 blocks
==28984== total heap usage: 143,095 allocs,143,095 frees,8,022,392 bytes allocated
==28984==
==28984== All heap blocks were freed -- no leaks are possible
==28984==
==28984== For counts of detected and suppressed errors,rerun with: -v
==28984== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
输出:
lalaland.txt
解决方法
您的内循环条件是错误的,导致您超出范围。它始终受第一个参数strlen(*argv)
的限制(由于使用了较早的argv++
),即使处理第二个及后续参数也是如此。由于您读出的长度为"hello"
,因此您过度读取了"baby"
,而无法读取所有的"yoyoyo"
。用一个字符过度读baby
最终会向NUL
写一个stdout
,我猜您的终端正在以类似于换行的方式进行解释。
我建议:
- 解决该问题,以便您使用每个参数的长度来打印它,并且
- 用简单的数组索引语法替换难以理解的指针算法
最终结果如下:
int main(int argc,char **argv)
{
for (int i = 1; i < argc; i++) // Adjust bounds to loop over provided args without mucking with argv directly
{
for (int j = 0; j < strlen(argv[i]); j++) // Loop to length of current arg
{
putchar(argv[i][j]);
}
printf("\n");
}
}