1

In C I understand that by using malloc() you can occasionally allocate memory that contains some junk data if you never used memset() or used calloc() instead.

How often does picking up junk data occur?

Is there a safe way to avoid this without having to use calloc() or memset() every single time?

CCoder
  • 2,305
  • 19
  • 41
kikiotsuka
  • 79
  • 8

4 Answers4

5

You must always be worried about picking up "junk data" and initialize the allocated memory to something meaningful in your program.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
3

There is no promise that memory allocated via malloc will be initialized to a given value.

You should make sure your constructors initialize variables, and that you memset allocated memory to a sane value.

gdc
  • 545
  • 12
  • 23
3

The malloc() function basically gets memory from two different places:

  1. It requests memory directly from the operating system (the kernel). On Unix systems such as Linux and OS X, this is done with the mmap() or sbrk() system calls. Memory from the kernel is always zero-initialized to begin with.

  2. It reuses memory that was freed earlier with free(). This is always assumed to be full of junk.

Just use calloc(). The calloc() function knows which pool the memory came from. If it came from the OS, then it's already zero-initialized and you get zeroed memory for free. If the memory is from free(), then calloc() will zero it for you. See why malloc+memset is slower than calloc for more details.

Summary for the lazy: The calloc() function already performs the optimization you are thinking of.

Community
  • 1
  • 1
Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
0

Is there a safe way to avoid this without having to use calloc() or memset() every single time?

There is, at least in Windows. Call VirtualAlloc() directly:

VirtualAlloc function (Windows)
Reserves or commits a region of pages in the virtual address space of the calling process. Memory allocated by this function is automatically initialized to zero, unless MEM_RESET is specified.

Alexey Frunze
  • 61,140
  • 12
  • 83
  • 180