Following pointer returned by malloc(0)

二次信任 提交于 2020-01-07 02:35:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!