#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;
}
当我提供长度不超过 17 个字符的小输入时(例如“aaaaaaaaaaaaaaaaaa”),程序工作得很好,但在提供更大长度的输入时,它给我一个运行时错误,提示“main.c 意外停止工作” .
我的编译器(代码块)或我的电脑(Windows 7)有问题吗?或者它与 C 的输入缓冲区有某种关系?
最佳答案
是 undefined behaviour 因为指针未初始化。你的编译器没有问题,但你的代码有问题:)
在将数据存储到那里之前,使 s
指向有效的内存。
要管理缓冲区溢出,您可以在格式说明符中指定长度:
scanf("%255s", s); // If s holds a memory of 256 bytes
// '255' should be modified as per the memory allocated.
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;
}
关于c - 在 char 指针中获取字符串输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14707427/