为什么';此C代码是否会更改字符串并导致缓冲区溢出?
我写了这段代码为什么';此C代码是否会更改字符串并导致缓冲区溢出?,c,string,pointers,C,String,Pointers,我写了这段代码 #include <stdio.h> int main() { char String[] = "Hello the world!"; char *pointer = String; int i; printf(" %s\n", pointer); pointer = "Helllooooo the worlldddddd"; printf("Hello %s\n", pointer); printf("H
#include <stdio.h>
int main()
{
char String[] = "Hello the world!";
char *pointer = String;
int i;
printf(" %s\n", pointer);
pointer = "Helllooooo the worlldddddd";
printf("Hello %s\n", pointer);
printf("Hello %s\n", String);
return 0;
}
但我得到了这个输出
Hello the world!
Hello Helllooooo the worlldddddd
Hello Hello the world!
如您所见,它无法更改
字符串值,但它显示的字符数超过了原始字符数。这不应该导致缓冲区溢出吗?这不会破坏其他变量吗?当你写这行的时候
pointer="Helllooooo the worlldddddd";
您不是说“获取指针指向的数组,并用字符串覆盖其内容”hellloooo the worlldddddd“
”,而是说“更改指针指向的字符串,使其现在指向字符串”,“hellloooo the worlldddddd”
。“这就解释了为什么在直接打印字符串
时会看到原始字符串被打印出来-实际上您从未对其进行过修改。因此,您不必担心数组溢出,因为您实际上并没有向它写入任何内容
另一方面,如果你写
strcpy(pointer, "Helllooooo the worlldddddd");
实际上,它会将新字符串的内容复制到指针指向的缓冲区中,那么就会出现缓冲区溢出,这将是一个问题。但请注意,这是一个非常不同的操作,它明确表示“请将此字符串的内容复制到此位置”,而不是“更改此指针指向的位置”。您已初始化一个指针,该指针指向字符串“Hello the world”char*pointer=string代码>目前为止一切正常。
第一个printfprintf(“%s\n”,指针)代码>,您已经打印了指向“世界你好”的指针。
然后将指针设置为指向一个新字符串“hellloooootheworlddddddd”pointer=“hellloooootheworlddddddd”代码>
然后您已经打印了指针,该指针在本例中指向“hellloooootheworlldddd”printf(“Hello%s\n”,指针)代码>
上次打印您打印了字符串“Hello the world”printf(“Hello%s\n”,字符串)代码>
注:。
(您在第二版代码中打印的TAKECALE)(PrTHF(%s\n),字符串);< /COD>和第三PROTFF <代码> PROTF(“hello %s\n”,字符串);< /COD>将在指针或字符串的值之前打印的字符串hello) 在操作字符串时要考虑的一个更快速选项:
string函数允许通过一个简单的步骤将现有字符串复制到新创建的字符串中。(或者至少是一个将所有复杂性都抽象掉的项目):
新字符串指针
现在可用于包含长度不超过len
的任何字符串,其中len
定义为:
int len = strlen(pointer);//len is 26 after using strdup(...); above
例如,因为示例字符串比len
短:
char String[]="Hello the world!";//length is 16
您可以将其复制到指针中
,而无需缓冲区溢出:
strcpy(pointer, String);
使用strdup(…):
创建的字符串需要释放以避免内存泄漏。使用完指针后调用以下命令:
free(pointer);
#包括
int main()
{
char String[]=“你好,世界”;//字符串
char*pointer=String;//指向字符串的指针
char i;//计数器
printf(“%s\n”,指针);//打印指针的当前值
pointer=“number of char”;//替换字符串的新值
for(i=0;i“你好,世界!”
和“Helloooo the worlldddddd”
是两个不同的字符串,位于内存的两个不同部分。使用指针=…
,可以将指针设置为这些字符串中任何一个的地址(即,将其设置为指向该字符串)@JohnH-我不认为String
被视为const
,无论是隐式的还是其他的,因此尽管不能向String
添加更多的空间,例如使用realloc(…)
,它可以修改。如果它是隐式的const
,我认为它会抛出编译时错误,而不是运行时错误。是否存在您观察到的其他特定环境?@JohnH,没有String
必须是可变的。它不是指向字符串文本,而是一个完全独立的数组char
不是const
限定的。因此,就其本身而言,修改它是没有问题的。(不过,大小显然有问题。)
strcpy(pointer, String);
free(pointer);
#include <stdio.h>
int main()
{
char String[]="Hello the world"; // the string
char *pointer=String; // pointer to string
char i; //counter
printf(" %s\n",pointer); // print current value of pointer
pointer="number of char"; // new value to replace the string
for (i=0;i<14;i++) // you cannot change the content of array without using loop
{
String[i] = pointer[i]; // char i in string = ti char i in pointer
}
printf("Hello %s\n",pointer); // print value of pointer
printf("Hello %s\n",String); // print value of string
return 0;
}