C ++ Access to access violation record 0x0 ... setting int *

I looked through various questions both here and elsewhere, but I still cannot explain the access violation error that I receive. "Access violation entry location 0x00000000" corresponds to a NULL pointer, right? I declared an int pointer, and later try to set the value in this place. Should memory space be allocated when a pointer is declared? Forgive me if this is noobish, but I'm a lot more Java / AS3 guy.

Here is part of my code ...

int* input; char* userInput[1]; int* output; int _tmain(int argc, _TCHAR* argv[]) { while(1) { srand(time(0)); *input = (int)(rand() % 10); 

It is broken into the last line.

+4
source share
7 answers

Memory is allocated for the pointer, but the pointer itself still does not point anywhere. Use new to allocate memory for the pointer and free it with delete later.

+10
source

You pointed to it, but you never allocated memory for it. Global pointer variables are initialized to zero, so you are lucky that you get undefined behavior on the stack.

do input = new int before dereferencing.

+2
source

No. int* input; only declares a pointer to int, not the actual space needed to store the integer.

+1
source

No. No memory is allocated for pointers. You must highlight it yourself. (If you are in C ++, you should almost always use a smart pointer instead of a raw pointer)

+1
source

The memory for the pointer itself is reserved (enough to store the address), but not any pointer memory pointed to.

With your Java background, you will recognize this as similar to a NullReferenceException .

+1
source

Do you really need pointers? If you just need an int and a string, you can select them directly:

 int input; int output; std::string userInput; int _tmain(int argc, _TCHAR* argv[]) { while(1) { srand(time(0)); input = rand() % 10; 
0
source

"Do not allocate memory space when declaring a pointer" - memory in HEAP is allocated only when using a 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!

0
source

All Articles