试图在cstring中提供空间时崩溃

crash when trying to give a space in cstring

本文关键字:空间 崩溃 cstring      更新时间:2023-10-16

我写了一个控制台程序,如果我在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;
}