开发者

Ways to allocate memory in C

开发者 https://www.devze.com 2023-04-10 16:24 出处:网络
I\'m fighting with memory managment right now. It\'s verry funny for me :) Here is simple app which I wrote. I can a开发者_如何转开发llocate memory in two ways.

I'm fighting with memory managment right now. It's verry funny for me :)

Here is simple app which I wrote. I can a开发者_如何转开发llocate memory in two ways.

int main (int argc,  const char * argv[])
{
    int *x;
    int *z;

    x = malloc(sizeof(int));
    z = (int *)sizeof(int);

    free(x);
    free(z);
}

Is there any difference between the ways of memory allocating used in the code above ?


The second line doesn't allocate any memory, it's the equivalent of

z=(int *)4;

ie, z will point to the (unallocated and most likely non-existant) (virtual) memory at address 4. If you do something like:

*z=0;

your program will crash to an access violation.


Is there any difference between the ways of memory allocating used in the code above?

The first one allocates memory. The second one does not.


Yes. z = (int *)sizeof(int); isn't actually allocating memory. I believe the behavior is technically undefined, but since you are basically assigning z to some unknown portion of the heap. The corresponding call to free(z) could cause major issues if this is used in production code.

Of course, you do not have a corresponding call to free(z). You are freeing y. Since I don't know what y is, then I can't tell you what that will do.


You actually want to cast the malloc statement into an int pointer. So

x = (int *) malloc(sizeof(int))


You are not allocating memory for z, will cause segmentation fault if used.
If you are question is if or not you should typecast result of malloc it is better you don't. Please refer Do I cast the result of malloc? for more details.
Also a NULL check of the return value ofmalloc will do more good than bad!
Hope this helps!


The 2 statements should be combined .

The first allocates dynamic memory from the heap and returns a void pointer to that area. The second just makes a cast without allocating any memory.

The recommended way is :

int* a = (int *) malloc( sizeof(int ) );

Also you can use calloc which is the same as malloc, but it also initialize the allocated memory to 0 .

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号