简体   繁体   English

像这样分配 memory 有什么区别吗?

[英]Is there any difference on allocating memory like this?

I think i have a beginner doubt.我想我有一个初学者的疑问。 I don't know if it is a very stupid question, but there is any difference between this two cases:我不知道这是否是一个非常愚蠢的问题,但这两种情况有什么区别:

Generic struct:通用结构:

typedef struct {

    void* data;

} Object;

1st case: This case allocates memory on a pointer and then, the pointer is returned.第一种情况:这种情况在指针上分配 memory 然后返回指针。

Object* NewObject1(const void* data) {

    Object* This = (Object*)malloc(sizeof(Object));
    memcpy_s(&This->data, sizeof(void**), &data, sizeof(void**));

    return This;
}

2nd case: In this case, the memory is allocated on a pointer that was given by the user.第二种情况:在这种情况下,memory 分配在用户指定的指针上。

void NewObject2(Object** This, const void* data) {

    *This = (Object*)malloc(sizeof(Object));
    memcpy_s(&(*This)->data, sizeof(void**), &data, sizeof(void**));

}

The result, actually, is the same:结果,实际上是一样的:

int main(){

    Object* a = NewObject1((void*)10);
    printf("a->data = %d\n", (int)a->data);

    Object* b = NULL;
    NewObject2(&b, (void*)10);
    printf("b->data = %d\n", (int)b->data);

    return 0;
}

Output: Output:

a->data = 10
b->data = 10

So my question is: There is any real difference between allocating memory as in the first case or as in the second.所以我的问题是:在第一种情况或第二种情况下分配 memory 之间有什么真正的区别。 For example, memory safety, performance, etc.例如memory安全、性能等。

The two methods of returning a value the same.这两种返回值的方法相同。 You can either return by value, or use a pointer argument that points to where the "returned" value should be written.您可以按值返回,也可以使用指向应写入“返回”值的位置的指针参数。

However there are several other strange things with your code:但是,您的代码还有其他一些奇怪的事情:

  • Instead of memcpy_s , you should just write This->data = data;而不是memcpy_s ,你应该只写This->data = data; and (*This)->data = data;(*This)->data = data; respectively.分别。 And fix the const-correctness.并修复 const 正确性。
  • (void *)10 is probably not a valid address, this might cause a trap, bus error or other problem. (void *)10可能不是有效地址,这可能会导致陷阱、总线错误或其他问题。 (undefined behaviour if it is not the address of an actual object) (如果不是实际对象的地址,则为未定义行为)
  • Casting the result of malloc is redundant or worse.铸造 malloc 的结果是多余的或更糟。
  • The return value of malloc should be checked.应检查 malloc 的返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM