问题
I am trying to understand a portion of code. I am leaving out a lot of the code in order to make it simpler to explain, and to avoid unnecessary confusion.
typedef void *UP_T;
void FunctionC(void *pvD, int Offset) {
unsigned long long int temp;
void *pvFD = NULL;
pvFD = pvD + Offset;
temp = (unsigned long long int)*(int *)pvFD;
}
void FunctionB(UP_T s) {
FunctionC(s, 8);
}
void FunctionA() {
char *tempstorage=(char *)malloc(0);
FunctionB(tempstorage);
}
int main () {
FunctionA();
return 0;
}
Like I said, I am leaving out a ton of code, hence the functions that appear useless because they only have two lines of code.
What is temp
? That is what is confusing me. When I run something similar to this code, and use printf()
statements along the way, I get a random number for pvD
, and pvFD
is that random number plus eight.
But, I could also be printing the values incorrectly (using %llu
instead of %d
, or something like that). I am pretty sure it's a pointer to the location in memory of tempstorage
plus 8. Is this correct? I just want to be certain before I continue under that assumption.
回答1:
The standard specifies that malloc(0)
returns either NULL or a valid pointer, but that pointer is never to be dereferenced. There aren't any constraints regarding the actual implementation, so you can't rely on the returned pointer being another plus 8.
回答2:
It's random in the sense that malloc
is typically non-deterministic (i.e. gives different results from run to run).
The result of malloc(0)
is implementation-defined (but perfectly valid), you just shouldn't ever dereference it. Nor should you attempt to do arithmetic on it (but this is generally true; you shouldn't use arithmetic to create pointers beyond the bounds of the allocated memory). However, calling free
on it is still fine.
来源:https://stackoverflow.com/questions/14102850/following-pointer-returned-by-malloc0