On Tue, 17 Dec 2013 22:38:24 -0800 (PST), pallav singh
Post by pallav singh
I have lot of legacy code having following conversion . please do let me know what’s the usage of this conversion
Case - 1
void * X;
X = *((void **)(X)); // whats the usage of this conversion
Case - 2
char * tmpstr1;
tmpstr1 = (char *)malloc(7);
strcpy(tmpstr1 , “monday”);
tmpstr1 = ‘\0’;
char * tmpstr2;
tmpstr2 = (char *)malloc(7);
strcpy(tmpstr2, *(char **)tmpstr1); // whats the usage of this conversion
tmpstr2 = ‘\0’;
This feels like homework, but I'll give you the benefit of doubt.
When trying to decipher pointer code, draw a picture of the structure
(or alternatively, walk through it as below).
You have a void* X which points to something, call it W for "whatzit".
Casting doesn't change the value of a pointer [at least not normally -
there are exceptions using multiple inheritance in C++ but they don't
apply here]. Casting does change the interpretation of the values.
We'll introduce a new pointer P to hold the intermediate.
void* X = &W;
// void* X --> void W
void** P = (void**)X;
// [void** P] --> [void* W] --> [void ?]
X = *P;
// [void* X] --> [void ?]
// X gets value of W which points to ?
The effect of X = *((void **)(X)) is to create a void pointer from
the void value pointed to by X and assign the pointer to X.
This may or may not be a mistake - there are occasions to do things
like this, e.g., a library manipulating opague types (though the
indirection is strange unless there is some kind of table further
involved in accessing the concrete type).
Case 2 definitely *is* a mistake - the input pointer being passed to
strcpy is composed of characters from the string "monday". strcpy
then is copying an unknown string of unknown length into tmpstr2,
potentially overwriting memory adjacent to the result buffer.
Moreover, the '\0' assignments are redundant - strcpy is defined to
copy the trailing null ('\0') of its input string. The static string
"monday" has a hidden null at the end.
If case 2 is real code, it either doesn't work or it is deliberately
obfuscating pointers by hiding them in static data. In either event,
whoever wrote it should be re-educated with a clue bat.