LinuxQuestions.org
Did you know LQ has a Linux Hardware Compatibility List?
Go Back   LinuxQuestions.org > Forums > Linux Forums > Linux - General
User Name
Password
Linux - General This Linux forum is for general Linux questions and discussion.
If it is Linux Related and doesn't seem to fit in any other forum then this is the place.

Notices

Reply
 
Search this Thread
Old 11-10-2010, 11:32 PM   #1
chaitanyajun12
Member
 
Registered: Nov 2010
Posts: 38

Rep: Reputation: 0
in linux malloc() initializes to zero.


#include<stdio.h>
#include<stdlib.h>

int main()
{
char *ptr;
ptr = (char *)malloc(10);
printf("%d...",(int)*ptr);
}

when i run this program, malloc is intializing the allocated memory to
zero. Whats the reason?
 
Old 11-11-2010, 12:14 AM   #2
Dark_Helmet
Senior Member
 
Registered: Jan 2003
Posts: 2,786

Rep: Reputation: 368Reputation: 368Reputation: 368Reputation: 368
From man malloc (emphasis added):
Quote:
malloc() allocates size bytes and returns a pointer to the allocated
memory. The memory is not cleared. If size is 0, then malloc()
returns either NULL, or a unique pointer value that can later be suc‐
cessfully passed to free().
No, malloc is not initializing your memory to anything. Each byte can be 0 just as easily as anything else. Perhaps the memory block allocated to your process was never used by another process. Perhaps the last process that used it set the memory to 0's before finishing. Perhaps a block of all 0's meant something to the last process that used the memory.

You cannot conclude that malloc() is doing something because you observe a result you do not expect. Your logic would require that malloc() actually intentionally scramble memory before giving it to a process just to make sure the process got random junk.
 
Old 11-11-2010, 12:22 AM   #3
macemoneta
Senior Member
 
Registered: Jan 2005
Location: Manalapan, NJ
Distribution: Fedora x86 and x86_64, Debian PPC and ARM, Android
Posts: 4,593
Blog Entries: 2

Rep: Reputation: 326Reputation: 326Reputation: 326Reputation: 326
Security, so you can't peek at previously allocated memory from another process. You can get non-zero memory if it was previously freed by your process. See:

http://www.mail-archive.com/freebsd-.../msg37534.html
 
Old 11-11-2010, 12:30 AM   #4
Dark_Helmet
Senior Member
 
Registered: Jan 2003
Posts: 2,786

Rep: Reputation: 368Reputation: 368Reputation: 368Reputation: 368
Hmmmmm.... well, perhaps I'm wrong in a roundabout way, but I could swear I've been burned by first-allocation, uninitialized, non-zero junk memory before.

Regardless, I've developed the habit of zero-filling my memory reservations. So maybe I just didn't notice the change.
 
Old 11-11-2010, 05:12 AM   #5
chaitanyajun12
Member
 
Registered: Nov 2010
Posts: 38

Original Poster
Rep: Reputation: 0
i got the same program on two systems it was just 0.
That was the reason i asked it?

i have one doubt..
As soon as process terminates its memory gets freed up. right?
After freeing is it initialized to zero?
 
Old 11-11-2010, 05:14 AM   #6
estabroo
Senior Member
 
Registered: Jun 2008
Distribution: debian, ubuntu, sidux
Posts: 1,094
Blog Entries: 2

Rep: Reputation: 111Reputation: 111
If you want it guaranteed to be zero after allocation just use calloc instead of malloc. If another process used that memory you'll get some value other than what it placed there I'm guessing 0 is the wipe value of choice for that, but you can malloc space you previously malloc'd in the same program and not get 0 values

Last edited by estabroo; 11-11-2010 at 05:17 AM.
 
Old 11-12-2010, 01:24 AM   #7
chaitanyajun12
Member
 
Registered: Nov 2010
Posts: 38

Original Poster
Rep: Reputation: 0
how to malloc the space we malloc'd in the same program.
Plz give an example.

Chaitanya.
 
Old 11-12-2010, 07:16 AM   #8
estabroo
Senior Member
 
Registered: Jun 2008
Distribution: debian, ubuntu, sidux
Posts: 1,094
Blog Entries: 2

Rep: Reputation: 111Reputation: 111
malloc a large chunk, write stuff to it, some pattern easy to spot (store the pointer you got)
free it
malloc another chunk (you can compare the pointer to the original)

most likely that second malloc will fall across the same memory and if the OS hasn't remapped the underlying physical memory you'll usually get the same chunk or something that falls across the space of the original chunk.

Code:
#include<stdio.h>
#include<stdlib.h>

int main(int argc, char* argv[]) {

        char* ptr;
        char* ptr_a;
        int   i;

        ptr_a = malloc(100000);
        if (ptr_a != NULL) {
                ptr = ptr_a;
                for (i=0; i < 100000; i++) {
                        ptr[i] = 0x5A;
                }
                free(ptr_a);
                ptr_a = malloc(100000);
                printf("ptr %p, ptr_a %p\n", ptr, ptr_a);
                for (i=0; i < 100000; i++) {
                        if (ptr_a[i] == 0x5A) {
                                break;
                        }
                }
                if (i != 100000) {
                        printf("found pattern at %d\n", i);
                }
        }
}
 
Old 11-12-2010, 08:52 AM   #9
johnsfine
Guru
 
Registered: Dec 2007
Distribution: Centos
Posts: 5,045

Rep: Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100
estabroo has answered this, so maybe my post is redundant. But I'm not sure estabroo's would be understood by those that didn't already know the answer:

Quote:
Originally Posted by Dark_Helmet View Post
Hmmmmm.... well, perhaps I'm wrong in a roundabout way, but I could swear I've been burned by first-allocation, uninitialized, non-zero junk memory before.
No, you were right the first time. The fact that malloc doesn't zero fill the memory means you can't rely on the memory being zero filled. Of course you also can't rely on the memory not being zero filled.

Linux zero fills the memory when it creates new pages of anonymous memory for your task. The first allocations (from malloc) by a simple program almost certainly are first uses of memory that was zero filled by Linux. But maybe some library routine has injected some startup code into the things that happen before main(). That is common in C++. I'm not sure what might happen in pure C. Maybe that startup code allocates and frees some memory. Maybe that is the memory you get on what you think is the first call to malloc. So even when calling malloc before any free has been called (by your code) I would not want to trust that the memory is still zero filled.

As estabroo explained, once you are getting memory from malloc that your own process previously gave back with free, you are getting left over contents of what was freed.

Quote:
Originally Posted by Dark_Helmet View Post
Your logic would require that malloc() actually intentionally scramble memory before giving it to a process just to make sure the process got random junk.
BTW, a common and useful debugging aid (that is turned on by default when you debug in Visual Studio) is that malloc does actually fill memory with a specific nonzero pattern. So code that depends on uninitialized memory being zero will break when you debug it in Visual Studio. Quite a lot of otherwise hard to find bugs are caught that way, so it is a very useful feature.

Last edited by johnsfine; 11-12-2010 at 08:57 AM.
 
Old 11-12-2010, 07:22 PM   #10
Dark_Helmet
Senior Member
 
Registered: Jan 2003
Posts: 2,786

Rep: Reputation: 368Reputation: 368Reputation: 368Reputation: 368
@johnsfine:

Thank you for clearing that up. I didn't completely follow the thought process in the email exchange you linked. In brief, I thought it was trying to say that when a process was spawned, a virtual memory space was created, that the virtual memory space was zero-filled, and therefore it would be impossible to get junk on a first-malloc(). Regardless, I feel like I should go review memory space terminology. I get the feeling I'm still missing something.

Quote:
BTW, a common and useful debugging aid (that is turned on by default when you debug in Visual Studio) is that malloc does actually fill memory with a specific nonzero pattern.
Although I don't use the Visual Studio stuff, I implement something similar at times. I read in some book the suggestion to fill dynamically allocated memory with a recognizable pattern rather than 0's or pure random data. So, I will sometimes use a couple of preprocessor "DEBUG" ifdefs that define either 0x00000000 or 0xDEADBEEF as the pattern to initialize dynamic memory. It works too. You open a debugger, add a couple watches, and facepalm when you see a permutation of 0xDEADBEEF in the data the program is croaking on. Good stuff.
 
Old 11-13-2010, 12:08 AM   #11
chaitanyajun12
Member
 
Registered: Nov 2010
Posts: 38

Original Poster
Rep: Reputation: 0
thank u all ...really helpful stuff.!
Thank u so much.
 
Old 11-13-2010, 07:25 AM   #12
johnsfine
Guru
 
Registered: Dec 2007
Distribution: Centos
Posts: 5,045

Rep: Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100
Quote:
Originally Posted by Dark_Helmet View Post
@johnsfine:

Thank you for clearing that up. I didn't completely follow the thought process in the email exchange you linked.
You mean the email exchange macemoneta linked.

Quote:
In brief, I thought it was trying to say that when a process was spawned, a virtual memory space was created, that the virtual memory space was zero-filled, and therefore it would be impossible to get junk on a first-malloc().
That is what it was saying and is roughly true. I was trying to point out one of the complications that you might not be able to be sure a malloc is necessarily a first-malloc (sure it isn't reusing space your own process's internal startup code already used and released).
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Wine - Photoshop initializes then crashes dbc001 Linux - Software 3 11-11-2012 11:21 AM
[SOLVED] Ubuntu Karmic no longer initializes RAM at startup skykooler Ubuntu 5 04-25-2010 06:32 PM
GRUB only Initializes when the Comp is restarted lupusarcanus Linux - Newbie 3 11-06-2009 06:43 AM
Modem initializes OK but I get error for username password indy_troglodyte Linux - Newbie 4 10-25-2008 03:06 PM
install stops after x initializes. dbcalo Fedora - Installation 5 11-01-2006 05:06 AM


All times are GMT -5. The time now is 06:48 AM.

Main Menu
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration