【发布时间】:2013-03-07 02:07:35
【问题描述】:
我觉得这个帖子有点迟钝,但我不知道为什么我的程序在从键盘读取字符串文字时会爆炸(即,然后将其分配给指针)。
调试了一个多小时,程序从键盘读取时一直在爆炸。
我已尽一切努力解决此问题。将字符串初始化为字符串文字(即编译器说它有 nullptr 问题)。这几乎就像我在某个地方有一个看不见的角色。如果有人能告诉我我做错了什么,我将不胜感激。
main.cpp
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#include <iostream>
#include <fstream>
#include "protocol.h"
int main()
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
int menuChoice = 0;
char * fileName = nullptr;
char * byteArray = nullptr;
char * hexArray = nullptr;
int numberOfBytes = 0;
PrintMenu();
GetMenuChoice(menuChoice);
ExecuteMenuChoice(menuChoice, fileName, byteArray, hexArray, numberOfBytes);
return 0;
}
protocol.cpp
void GetFile(char * fileName)
{
//Prompt user for binary file
std::cout << "\nEnter filename: " << std::endl;
//Read in location of binary file
std::cin.ignore(std::cin.rdbuf()->in_avail());
std::cin.getline(fileName, 256);
std::cin.clear();
std::cin.ignore(std::cin.rdbuf()->in_avail());
}
protocol.h
#ifndef PROTOCOL_H
#define PROTOCOL_H
//Function declarations
void PrintMenu();
void GetMenuChoice(int &menuChoice);
void ExecuteMenuChoice(int menuChoice, char *& fileName, char *& byteArray,
char *& hexArray, int numberOfBytes);
void NewLine();
void ThankUser();
void ErrorMessage();
#endif
【问题讨论】:
-
它不是字符串文字,除非它是源代码中存在的字符串。
-
我马上怀疑
std::cin.getline(fileName, 256);。但是你甚至没有展示它是如何被使用的。重现问题的最小示例在哪里? -
“程序不断炸”是什么意思?
-
丢失
char *fileName(就此而言所有此代码中的char *s)并改用std::string。 -
我同意,这个问题会比较尴尬……