版权声明:转载请声明 https://blog.csdn.net/qq_40732350/article/details/83902910
当我们定义了一个字符串常量并且用一个指针指向它,这时有一个不容易发现的严重BUG。
如下面这样定义:
const char *p = "s a ";
printf("n = [%d]\n", my_run(a));
编译会在这样存放常量:s a n = [%d]\n'\0'
这里可以发现一个BUG,就是*p指向的字符串没有加上'\0',本来应该是这样:s a '\0'n = [%d]\n'\0'
这样会带来一些麻烦,就如下面的程序。
#include <stdio.h>
#include <stdlib.h>
int my_run(const char *input_str)
{
const char *str_p = input_str;
int n = 0;
for(; str_p != '\0'; str_p++)
{
if((*str_p != 32) && (*(str_p + 1) == '\0')){
++n;
break;
}
if(*str_p == 32)
{
printf("n = [ %c ]\n",* str_p );
++n;
}else{
printf("n = [ %c ]\n",* str_p );
}
}
return n;
}
int main(void)
{
const char *a = "s a ";
printf("n = [%d]\n", my_run(a));
return 0;
}
运行结果:
n = [ s ]
n = [ ]
n = [ a ]
n = [ ]
n = [ ]
n = [ n ]
n = [ ]
n = [ = ]
n = [ ]
n = [ [ ]
n = [ % ]
n = [ d ]
n = [ ] ]
n = [5]
但是当我们在定义字符串是不是以空格结尾就没问题,下面的程序可以证明
#include <stdio.h>
#include <stdlib.h>
int my_run(const char *input_str)
{
const char *str_p = input_str;
int n = 0;
for(; str_p != '\0'; str_p++)
{
if((*str_p != 32) && (*(str_p + 1) == '\0')){
++n;
break;
}
if(*str_p == 32)
{
printf("n = [ %c ]\n",* str_p );
++n;
}else{
printf("n = [ %c ]\n",* str_p );
}
}
return n;
}
int main(void)
{
const char *a = "s a a";
printf("n = [%d]\n", my_run(a));
return 0;
}
运行结果:
n = [ s ]
n = [ ]
n = [ a ]
n = [ ]
n = [3]
总结:
这里的BUG就是编译器的问题,只有我们自己来避免这个BUG。