#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(){
char *s;
printf("enter the string : ");
scanf("%s", s);
printf("you entered %s\n", s);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我提供长度不超过17个字符的小输入时(例如"aaaaaaaaaaaaaaa"),程序工作得非常好,但是在提供更大长度的输入时,它会给我一个运行时错误,说"main.c已经意外停止工作".
我的编译器(代码块)或我的电脑(Windows 7)有问题吗?或者它是否与C的输入缓冲区有关?
P.P*_*.P. 20
它是未定义的行为,因为指针未初始化.您的编译器没有问题,但您的代码有问题:)
让s在里面存储数据前点有效的内存.
要管理缓冲区溢出,可以在格式说明符中指定长度:
scanf("%255s", s); // If s holds a memory of 256 bytes
// '255' should be modified as per the memory allocated.
Run Code Online (Sandbox Code Playgroud)
GNU C支持非标准扩展,如果%as指定了分配,则不必分配内存,但应传递指针指针:
#include<stdio.h>
#include<stdlib.h>
int main() {
char *s,*p;
s = malloc(256);
scanf("%255s", s); // Don't read more than 255 chars
printf("%s", s);
// No need to malloc `p` here
scanf("%as", &p); // GNU C library supports this type of allocate and store.
printf("%s", p);
free(s);
free(p);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
char指针未初始化,你应该动态地为它分配内存,
char *s = malloc(sizeof(char) * N);
Run Code Online (Sandbox Code Playgroud)
其中N是您可以读取的最大字符串大小,并且在不scanf
指定输入字符串的最大长度的情况下使用它是不安全的,请像这样使用它,
scanf("%Ns",s);
Run Code Online (Sandbox Code Playgroud)
其中N与malloc相同.