howDidMyCodeWork
howDidMyCodeWork

Reputation: 391

Why does malloc seem to always return 0?

A website said that malloc doesn't set the value returned to zero.

So I decided to test it using this code:

#include<stdlib.h>
#include<stdio.h>
int main() {
    size_t is = sizeof(int);
    unsigned int *l = malloc(is);
    while((*l)==0) {
        free(l);
        l=malloc(is);
    }
    return 0;
}

Will this ever return or run forever.

I waited a while for it to stop but it hasn't.

Upvotes: 0

Views: 272

Answers (3)

Eric Postpischil
Eric Postpischil

Reputation: 222437

Generally, malloc does not set the memory it provides to zero. However, it may be zero for other reasons, such as that the operating system set it to zero when giving it to the process, and the process has not used it for anything else.

Therefore, you cannot expect that the memory will not be zero (and you cannot expect that it will be zero).

Upvotes: 1

Nathan
Nathan

Reputation: 693

As the manual says, malloc() return a void *, so a void-type pointer. depending on the case, the returned value change:

  • If malloc() is called with a size of 0, it will return NULL.
  • In case of any error, malloc() will return NULL.
  • If no problems are encountered, malloc will return a pointer to the allocated memory.

So when calling to malloc(), you will get an allocated space, randomly in your memory. And that's all. The malloc() function does not set values, or change data already written in memory; it will just return an address to a free space.

If you want to initialize values in an array, you should use the memset() function (man 3 memset).

Upvotes: 0

ikegami
ikegami

Reputation: 385655

You're not checking the value returned by malloc. In fact, malloc almost surely didn't return zero/NULL since that would result in a SIGSEGV on most systems.

You're checking what's at the address pointed by the pointer returned by malloc. That's not guaranteed to be zero or anything else, and it's Undefined Behaviour to read uninitialized memory. There's no point in discussing what happens when one invokes Undefined Behaviour.

Use calloc if you want initialized memory.

Upvotes: 3

Related Questions