Shani de Leeuw Shani de Leeuw - 1 year ago 52
C++ Question

Hash define to the first element of an array causing a null point exception

I have code that looks like this:

char* talk[516] = {(char*)1};
#define testValue (*(int*)talk[0])

I receive a null pointer exception when the following line of code is then called.

testValue = 0;

Why is that? Haven't all value of the
been initialised?


What I want to do is, there are 516 number values (
s and
s) which are stored in
should point to the
value that is stored in the first element of the array. The next value along might be
#define testValue2(*(float*)talk[1])

Answer Source

For char* talk[516] = {0};, all the elements (i.e char*) of talk are initialized with value 0 (i.e. null pointer).

For char* talk[516] = {(char*)1};, the 1st element of talk is initialized with value 1, which is not a valid value for pointer. (And the other elements are still initialized as null pointer.) *(int*)talk[0] fails, because you're trying convert a char* to int*, which points to memory address 1, and then dereference on it.

You should initialize elements with valid value, such as:

int i;
float f;
void* talk[516] = {&i, &f, /*...*/};

#define testValue (*(int*)talk[0]) 
#define testValue2 (*(float*)talk[1]) 

testValue = 1; 
testValue2 = 1.5; 

1. Note if use new to initialize elements of talk, you need to delete them at last.
2. You could use loop to initialize talk too.
3. Using char* instead of void* is confusing, IMO.
4. Consider about using std::map instead of macro magic.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download