试图在cstring中提供空间时崩溃
crash when trying to give a space in cstring
我写了一个控制台程序,如果我在fp->kind中给一个空格,它就会崩溃。这是我的密码。
#include <iostream>
struct fish
{
char kind[40];
float lenght;
float weight;
};
int main()
{
using std::cout;
using std::cin;
fish* fp = new fish();
cout<<"enter the kind of fish: ";
cin>>fp->kind;
cout<<"nenter the weight of the fish: ";
cin>>fp->weight;
cout<<"nenter the lenght of the fish: ";
cin>>fp->lenght;
cout<<"nKind: "<<fp->kind
<<"nlenght: "<<fp->lenght
<<"nweight: "<<(*fp).weight;
cin.get();
cin.get();
delete fp;
return 0;
}
如果我不给它一个空间,它就不会崩溃。
PS im使用Visual Studio 2012。这是调试输出。
'Project1.exe' (Win32): Loaded 'C:UsersDark VadarDocumentsVisual Studio 2012ProjectsProject1DebugProject1.exe'. Symbols loaded.
'Project1.exe' (Win32): Loaded 'C:WindowsSystem32ntdll.dll'. Cannot find or open the PDB file.
'Project1.exe' (Win32): Loaded 'C:WindowsSystem32kernel32.dll'. Cannot find or open the PDB file.
'Project1.exe' (Win32): Loaded 'C:WindowsSystem32KernelBase.dll'. Cannot find or open the PDB file.
'Project1.exe' (Win32): Loaded 'C:WindowsSystem32msvcp110d.dll'. Symbols loaded.
'Project1.exe' (Win32): Loaded 'C:WindowsSystem32msvcr110d.dll'. Symbols loaded.
The program '[1848] Project1.exe' has exited with code 0 (0x0).
cin
使用空白来分隔输入令牌。示例:
//Input: apples oranges
cin >> str1;
cin >> str2;
//You get str1 = "apples", str2 = "oranges"
在代码中,如果为第一个cin>>
提示(如"A B")输入空格。
fp->kind设置为"A"
fp->weight设置为"B",cin接下来读取该值并尝试转换为float,但失败。
您需要使用getline来读取整行。
#include <string>
//...
struct fish
{
std::string kind;
float lenght;
float weight;
};
是正确的实现,没有原始数组引发的漏洞。
顺便说一句,崩溃不是由输入空白引起的,而是由缓冲区溢出引起的。
这样就可以了。它不会像上面提到的Jule那样导致任何漏洞,并且会在"种类"字段中占用任何数量的空格或超特殊字符。请注意,这使用默认的c流。我使用这些是因为它们可以被严格控制。请注意scanf中"%"后面的"39"。这将阻止它读取超过39个字符,从而为null终止符多留一个位置。
#include <cstdio>
using namespace std;
struct fish
{
char kind[40];
float length;
float weight;
};
int main()
{
fish* fp = new fish();
printf("enter the kind of fish: ");
scanf("%39[^n]", fp->kind);
printf("enter the weight of the fish: ");
scanf("%f", &(fp->weight));
printf("enter the length of the fish: ");
scanf("%f", &(fp->length));
printf("nKind: %snlength: %fnweight: %fn", fp->kind, fp->length, fp->weight);
delete fp;
return 0;
}
相关文章:
- 当回溯以零开始时,如何调试崩溃
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 命名空间中具有.h和.cpp文件的类
- 从父命名空间重载类型
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 在命名空间中定义函数还是限定函数
- 内联映射初始化的动态atexit析构函数崩溃
- 执行函数时导致崩溃的变量
- C++:对不存在的命名空间使用命名空间指令
- 程序崩溃并显示"std::out_of_range"错误
- 通过继承类使用来自不同命名空间的运算符
- CoInitialize()在单独的线程上崩溃而不返回
- 使用命名空间时出现多个定义错误
- 使用调试/崩溃报告将应用程序部署到客户端
- OpenGL相机和相机空间转型的困惑
- CUDA内核和数学函数的显式命名空间
- Android Studio-用户名空间导致崩溃,NDK没有安装到此目录
- Apache 崩溃并显示错误 R6016 没有足够的空间来存储线程数据
- 手动设置空间参照时,LibLas崩溃
- 试图在cstring中提供空间时崩溃