jingo
jingo

Reputation: 1074

Ways to allocate memory in C

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

Here is simple app which I wrote. I can allocate 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 ?

Upvotes: 1

Views: 376

Answers (6)

coredump
coredump

Reputation: 3107

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 .

Upvotes: 0

another.anon.coward
another.anon.coward

Reputation: 11395

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!

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612824

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.

Upvotes: 2

cwallenpoole
cwallenpoole

Reputation: 81988

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.

Upvotes: 1

Blindy
Blindy

Reputation: 67362

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.

Upvotes: 10

tekknolagi
tekknolagi

Reputation: 11012

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

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

Upvotes: 0

Related Questions