问题描述
我对以下代码有疑问:
int age = 20;
void * pointer;
pointer = alloc(sizeof(int), 0)
pointer = (void*) age;
它如何工作?
pointer
的值是什么?
这段代码在一行中会发生什么:
What happens with this piece of code in terms of the line :
pointer = (void*) age;
推荐答案
此代码完全不执行任何操作.
This code accomplishes exactly nothing.
首先,您使用非标准的分配方法为int
的大小分配了一个指针.
First, you allocated a pointer for a size of int
, using non-standard allocation methods.
然后,您将指针分配给指向地址0x14的地址,该地址可能不包含任何有效信息,并且如果尝试取消引用它,则会给出SEGFAULT.
Then, you assign that pointer to point to the address 0x14, which probably doesn't contain any valid information, and would give you a SEGFAULT if you attempted to dereference it.
第三,您泄漏了alloc
用于指针的初始内存,这从来都不是一件好事.
Third, you leak the initial memory you alloc
'd for pointer, which is never a good thing.
总体来说,这是一个非常糟糕的设计模式.
Overall, a VERY bad design pattern.
这篇关于将void *指针设置为等于整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!