由malloc(0)返回的跟随指针 [英] Following pointer returned by malloc(0)

查看:63
本文介绍了由malloc(0)返回的跟随指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解部分代码.为了简化说明并避免不必要的混乱,我遗漏了很多代码.

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.

什么是temp?那就是让我困惑的地方.当我运行类似于此代码的代码,并在整个过程中使用printf()语句时,会得到pvD的随机数,而pvFD是该随机数加8.

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.

但是,我也可能打印了错误的值(使用%llu而不是%d或类似的方法).我很确定这是指向tempstorage加8的内存位置的指针.这是正确的吗?我只是想确定一下,然后再继续执行该假设.

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.

推荐答案

标准指定malloc(0)返回NULL或有效的指针,但永远不要取消引用该指针.对实际的实现没有任何限制,因此您不能依赖于返回的指针是另一个加8.

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.

这篇关于由malloc(0)返回的跟随指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆