Like Tree1Likes
  • 1 Post By Ocifer

Some questions about memory allocation

This is a discussion on Some questions about memory allocation within the C++ Programming forums, part of the General Programming Boards category; Hi , I have some questions about memory allocation. When we use malloc function as: Eg. Code: malloc(7*(size of(int))); Does ...

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    96

    Some questions about memory allocation

    Hi ,

    I have some questions about memory allocation.

    When we use malloc function as:

    Eg.

    Code:
    malloc(7*(size of(int)));
    Does this mean that we are allocating memory space to data type "int" which is 7 times?

    Also as far as I know malloc function doesnot initialize the objects using any constructor nor it returns any type except for void.

    Do we have to define malloc function inside the main() function?

    I hope i am clear

    thanks

  2. #2
    Registered User
    Join Date
    Apr 2010
    Posts
    82
    All of these questions could be answered just by looking up "man pages malloc" on google. malloc() is a staple of C, but the "new" keyword is what you should use in c++. No you don't have to define malloc() inside the main. It is provided by including <stdlib.h> (for C) or <cstdlib> (for C++). Like I said though, "new" is meant for C++ use.

    Finally malloc returns a pointer to a chunk of memory dictated by 7*sizeof(int). So it finds what size an int is on your computer, you're multiplying by 7, so it will return a pointer to a chunk of memory which can store 7 integers. There is a page about malloc() and casting here: FAQ: Casting malloc?

    It can be hard to find information at first, but get used to googling.

    EDIT:

    A bit more nuanced than what I was willing to go:
    http://www.codeproject.com/Articles/...ix-them-is-sin
    Last edited by Ocifer; 02-02-2012 at 10:32 AM.
    rags_to_riches likes this.
    W7, Ubuntu -- mingw, gcc, g++, code::blocks, emacs, notepad++

  3. #3
    Registered User
    Join Date
    Apr 2010
    Posts
    82
    Also, it should be: sizeof() and NOT size of()

    ONE WORD.
    W7, Ubuntu -- mingw, gcc, g++, code::blocks, emacs, notepad++

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. memory allocation
    By lars-erik in forum C++ Programming
    Replies: 3
    Last Post: 08-29-2011, 08:24 AM
  2. help on memory allocation(?)
    By adameye in forum C Programming
    Replies: 3
    Last Post: 09-02-2009, 02:31 PM
  3. Memory allocation
    By kernelio in forum C Programming
    Replies: 6
    Last Post: 10-11-2007, 10:19 AM
  4. Memory Allocation
    By Strut in forum C++ Programming
    Replies: 7
    Last Post: 10-14-2002, 05:15 PM
  5. memory allocation
    By Dohojar in forum C Programming
    Replies: 10
    Last Post: 03-15-2002, 10:26 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21