C++ Access violation writing location 0x0... setting int *
I've looked through various questions both here and other places, but I still cannot explain the access violation error I'm getting. "Access violation writing location 0x00000000" corresponds to a NULL pointer, correct? I've declared an int pointer, and I later try to set a value at that location. Shouldn't the memory space be allocated when I declare the pointer? Forgive me if this is noobish, but I'm much more of a Java/AS3 guy.
Here is a portion of my code...
int* input;
char* userInput[1];
int* outpu开发者_如何学编程t;
int _tmain(int argc, _TCHAR* argv[])
{
while(1)
{
srand(time(0));
*input = (int)(rand() % 10);
It breaks at the last line.
Memory is allocated for the pointer, but the pointer itself still doesn't point anywhere. Use new
to allocate memory for the pointer to point to, and free it with delete
later.
You declared a pointer it but never allocated a memory for it to point to. Global pointer variables are initialized to zero, so you're lucky, on stack you'd get undefined behavior.
do input = new int
before dereferencing.
The memory for the pointer itself is reserved (enough to hold an address), but not any memory for the pointer to point to.
With your Java background, you'll recognize this as similar to a NullReferenceException
.
No. int* input;
declares only a pointer to an int, not the actual space required to hold an integer.
No. Memory space is never allocated for pointers. You have to allocate that yourself. (If you're in C++, you should almost always be using a smart pointer instead of a raw pointer for this)
"Shouldn't the memory space be allocated when I declare the pointer" - memory on the HEAP is only allocated when you use the new keyword. For instance,
int *ptr //creates a pointer variable on the stack
ptr = new int(5); //allocates space in heap and stores 5 in that space
hope this helps you!
Do you really need the pointers? If you just need some int
s and a string, you can allocate them directly:
int input;
int output;
std::string userInput;
int _tmain(int argc, _TCHAR* argv[])
{
while(1)
{
srand(time(0));
input = rand() % 10;
精彩评论