全部学习汇总: GreyZhang/c_basic: little bits of c. (github.com)

C语言中的puts函数式字符串处理比较好用的一个函数,传入值为数组名称或者是指向字符串的指针。

在功能实现上,我并没有去查看标准库的源代码。测试中遇到小问题才去借助网络寻找了一下答案。所找到的几个答案说的差不多,但是都不算深入,自己在此先做一下相应的总结后续再追查一下源码。

Puts输出功能会自动追加一个换行,结束的标志是遇到\0。我理解的是\0应该会占据字符串数组中的一个字节的位置,因此在函数输出遇到恰好被字符填充满的字符串(没有给\0留位置)时可能会遇到输出的乱码问题。

最初发现这个是出于一个小测试,在网络上看到有人说puts函数支持的字符串长度不能够超过255。但是尝试的时候发现255以上不会报错,于是写了一个小脚本想看看到多少会报错。

脚本:

#!/usr/bin/python
import os,time
code_temp = open('puts_test.c','r').read()
for i in range(5):
       array_num = 2 ** i
       print "array index :",array_num
       str_gen = 'a' * array_num
       code_output = code_temp.replace('string_test',str_gen)
       code_output = code_output.replace('array_num',str(array_num))
       fid = open('test.c','w');
       fid.write("%s" % code_output)
       fid.close()
       os.system('gcc test.c')
       time.sleep(2)
       print("result is:")
       os.system('a.exe')
       print('-' * 80)
其中,需要的代码puts_test.c如下:
#include "stdio.h"
int main(void)
{
       char test_string[array_num] = "string_test";
       puts(test_string);
       return 0;
}
执行结果中遇到最后一个字符乱码,其实修正也很简单,把数组扩充一位。Python脚本如下:
#!/usr/bin/python
import os,time
code_temp = open('puts_test.c','r').read()
for i in range(5):
       array_num = 2 ** i + 1
       print "array index :",array_num
       str_gen = 'a' * array_num
       code_output = code_temp.replace('string_test',str_gen)
       code_output = code_output.replace('array_num',str(array_num))
       fid = open('test.c','w');
       fid.write("%s" % code_output)
       fid.close()
       os.system('gcc test.c')
       time.sleep(2)
       print("result is:")
       os.system('a.exe')
       print('-' * 80)

测试的过程中简单测试到了2048,没有发现数组限制的问题,发现了边界乱码现象。继续测试,设置延时时间为10秒,最终测试到2^20个数值没问题,继续往下程序卡死。估计也没人会用到这么长的字符串吧!

如果测试到那么大的字符串,上面的脚本中延时时间是得加大一些,否则电脑报错。当然,电脑的内存首先得给力一点,不然耐不住折腾。