user2012481 user2012481 - 4 months ago 21
C++ Question

pointer and 0xDEADBEEF, why does this code not work?

I am trying to analyze some code in a C++ program (I am very new to C++), and I dont get what the following code is trying to accomplish.

Based on the threads Ive read on here, setting a pointer to deadbeef will make the pointer null. However, visual studio does not allow me to do this and gives me an error. I have no idea what the second pointer is supposed to do. Any input would be appreciated.

long* firstpointer = (long *)((void *)0);
char* secondpointer = (char*) ((void *)0);

*firstpointer = 0xDEADBEEF;
strcpy(secondpointer,"Here is some text, here is some more");

Answer

Based on the threads Ive read on here, setting a pointer to deadbeef will make the pointer null.

No, that is incorrect. Although deadbeef is a common "nonsense pattern", it is definitely not equal null. A common reason to set pointers (more generally, a memory area) to a known and unusual pattern, such as deadbeef, is to detect non-initialized areas of memory. A pattern of all zeros, which is commonly used to represent null pointers, is not as good a candidate, because your chances of finding a sequence of zeros in consecutive memory locations is much higher than finding a sequence of deadbeefs.

The crash that you see in the call of strcpy happens because secondpointer is set to an invalid value. You need to allocate enough memory to fit "Here is some text, here is some more", along with its terminating zero, in order for strcpy not to exhibit undefined behavior.