Ok so I’m doing a program for class when I run across a bug I’ve never seen before and no idea what to do about it with only minimal experience with using the debugger, so I’ve come here hoping someone here can set me down the path to fixing this bug. My bug is the access violation reading location. Here is the portion of code that seems to be giving me the error:
#include "Book.h"
using namespace std;
void add (char*, char*, int);
void remove (int&);
void list ();
int Count;
Book Bookshelf [4];
int main ()
{
char* In = "";
char* N = "";
char* A = "";
int Y;
int Num;
do
{
cout << "Bookshelf> ";
cin >> In;
if (In == "add")
{
cout << "Bookshelf> Enter book: ";
cin >> N >> A >> Y;
add (N,A,Y);
}
else if (In == "remove")
{
cout << "Bookshelf> Select number: ";
cin >> Num;
remove (Num);
}
else if (In == "list")
{
}
} while (cin != "quit");
return 0;
}
void add (char* N, char* A, int Y)
{
if (Bookshelf[4].IsEmpty() == false)
cout << "Error!" << endl;
else
{
Bookshelf[Count] = Book (N,A,Y);
Count++;
}
cout << "Bookshelf> ";
}
I get the error when I type add into the command line to try to call the add function but it happens immediately so the debugger is no help to me. I know the problem is probably really simple but I can’t seem to find it. Any help you can offer would be greatly appreciated. Let me know if any more code samples are needed.
You shouldn’t use
char*unless you really know what you are doing. For example, I rarely usechar*at all and I’m programming with C++ since about 20 years. You want to usestd::string, e.g. like this:The reason your code doesn’t work is that the input operator wants to store data at the location pointed to by your pointer. However, this pointer is pointing at immutable memory for a c-string literal. When the operator tries to store something at this location it immediately gets an access violation.
The easiest fix is to use
std::string. If you can’t usestd::stringfor whatever reason, use a preallocated array ofchar. If you do this, make sure you tell the stream how much characters are available by setting up the width:(the reason I’m always using a check in these example is that it is very important that you always check whether your input was successful before you do anything with the result).