Memory management - How/why/when

This is a discussion on Memory management - How/why/when within the C Programming forums, part of the General Programming Boards category; I'm new to c programming, but my main concern is the memory management? How? When? Why? should I allocate memory? ...

  1. #1
    Registered User
    Join Date
    Oct 2007
    Posts
    47

    Memory management - How/why/when

    I'm new to c programming, but my main concern is the memory management?

    How? When? Why? should I allocate memory?

    Code:
    int i;
    Do I need to allocate memory for i?

    Code:
    struct some_type *p;
    
    p = (some_typ *)malloc(sizeof(p));
    when I use pointers to structs I do as above, but is it only for pointers I need to allocate memory?

  2. #2
    Registered User Tommo's Avatar
    Join Date
    Jun 2007
    Location
    Scotland
    Posts
    101
    > Do I need to allocate memory for i?

    No.

    > p = (some_typ *)malloc(sizeof(p));

    Don't cast malloc. Also i think you'll be wanting sizeof(struct some_type) (or sizeof(*p)).

    > is it only for pointers I need to allocate memory?

    Pretty much. You don't need to allocate memory for char string[100], for example, but you do for char *string. Well, that's if you don't make it point to a character array instead:
    Code:
    char string[100], *str;
    str = string; /* str points to string[0] */
    Last edited by Tommo; 11-07-2007 at 05:23 AM.

  3. #3
    Registered User
    Join Date
    Nov 2007
    Posts
    4
    i'll try to explain it another way.
    if at the beginning of the program you know exactly how many data types and from which type - you are going to use in your program than you dont have to allocate memory at all.

    usually programmers are using this utility when they run a program and during the run they might need to create new data types, for example lets say my program contains an empty linked list and start to run an infinite loop, whenever the user enter an int the program adds another unit to the linked list with that int (every unit in the linked list will be a structure with an int to contain the user input and a pointer to the next unit) you see, i can't tell in advance how many unit (i.e. structures) im going to use in my program so in the infinite loop i'll have to allocate memory to create a new structure whenever the user enters an input int, i need to make sure there will be somewhere malloc() and of course at the end i'll have to free all the memory spaces i used.

    as for your example the structure could be defined in a program:

    struct some_type p;

    and than the memory is allocated as well, you dont have to use malloc,
    again use the memory allocation tools only if during the run of the program u need to dynamically allocate memory.

    i hope i've been helpfull,
    any questions??

  4. #4
    Registered User
    Join Date
    Apr 2007
    Posts
    45
    Do I need to allocate memory for i?
    i's memory is allocated automatically on the stack and gets freed automatically when you leave whatever routine you're in - be it another function or main.

    Anything allocated memory with malloc() is declared on the heap which does not automatically get freed - the data persists until it has been free()d.
    we are one

  5. #5
    lfs addicted
    Join Date
    Nov 2007
    Posts
    49
    Quote Originally Posted by Tommo View Post
    >
    > p = (some_typ *)malloc(sizeof(p));

    Don't cast malloc.
    ...
    why "don't cast malloc" ? because it is automatic or because it is wrong?

  6. #6
    Devil™
    Join Date
    Oct 2007
    Location
    IIT-Kharagpur, India
    Posts
    104
    Quote Originally Posted by micke_b View Post
    I'm new to c programming, but my main concern is the memory management?
    How? When? Why? should I allocate memory?
    if you understand the concept of pointers well you wont be asking this question..
    there are few things that generally are not covered in beginner books.. though they are related to pointers..
    they are good in their own way

    I found This Tutorial very useful, interesting and informative..
    there is a pdf version of that too..
    I am sure it will help you a lot if you go through it.. ( atleast go through chap 1,2 & 9)

    Quote Originally Posted by sloppy View Post
    why "don't cast malloc" ? because it is automatic or because it is wrong?
    faq helps
    Last edited by gibsosmat; 11-07-2007 at 07:19 AM.

  7. #7
    lfs addicted
    Join Date
    Nov 2007
    Posts
    49
    Quote Originally Posted by gibsosmat View Post
    if you understand the concept of pointers you wont be asking this question..
    there are few things that generally are not covered in beginner books.. though they are related to pointers..
    they are good in their own way

    I found This Tutorial very useful, interesting and informative..
    there is a pdf version of that too..
    I am sure it will help you a lot if you go through it.. ( atleast go through chap 1,2 & 9)


    faq helps
    I know what a pointer is, and from the pdf you linked I read that the casting of malloc is not wrong, it is just not needed and obsolete. (as I suspected above)

    Anyway thanks.
    Last edited by sloppy; 11-07-2007 at 07:02 AM. Reason: typo error

  8. #8
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,742
    > why "don't cast malloc" ? because it is automatic or because it is wrong?
    See the FAQ
    Yes, it's automatic.
    It's not wrong per-se, when the rest of the code is correct.
    However, there are some mistakes you can make which a cast will cover up, which can be very bad news down the line.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  9. #9
    Devil™
    Join Date
    Oct 2007
    Location
    IIT-Kharagpur, India
    Posts
    104
    Quote Originally Posted by sloppy View Post
    I know what a pointer is, and from the pdf you linked I read that the casting of malloc is not wrong, it is just not needed and obsolete. (as I suspected above)

    Anyway thanks.
    I should have been more clean in my last post..
    but the links I gave are not for you.. its for the person who started this thread..

    and the link I posted below your quote is for you.. faq explains it.. suppression of error variables
    in man pages malloc is not a stdio.h function..
    but it works as I think most of the compilers let it go..
    even if you dont include stdio.h the code compiles well.. but with warnings..
    so its always better not take warnings from compiler

  10. #10
    lfs addicted
    Join Date
    Nov 2007
    Posts
    49
    Quote Originally Posted by gibsosmat View Post
    I should have been more clean in my last post..
    but the links I gave are not for you.. its for the person who started this thread..
    My fault... I read in hurry :-P

  11. #11
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by gibsosmat View Post
    I should have been more clean in my last post..
    but the links I gave are not for you.. its for the person who started this thread..

    and the link I posted below your quote is for you.. faq explains it.. suppression of error variables
    in man pages malloc is not a stdio.h function..
    but it works as I think most of the compilers let it go..
    even if you dont include stdio.h the code compiles well.. but with warnings..
    so its always better not take warnings from compiler
    s/stdio/stdlib/ ?

    Also, consider that in some processor architectures & ABI combinations, a pointer may not always be returned in the same register as an integer value (e.g. integer values in D0, pointers in A0 in 68000 processors), in which case a non-prototyped malloc() would make the code break. Casting the call will potentially hide this and make the compiler not tell you that it will break.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  12. #12
    Devil™
    Join Date
    Oct 2007
    Location
    IIT-Kharagpur, India
    Posts
    104
    Quote Originally Posted by matsp View Post
    s/stdio/stdlib/ ?
    its in stdlib.h
    Quote Originally Posted by matsp View Post
    Also, consider that in some processor architectures & ABI combinations, a pointer may not always be returned in the same register as an integer value (e.g. integer values in D0, pointers in A0 in 68000 processors), in which case a non-prototyped malloc() would make the code break. Casting the call will potentially hide this and make the compiler not tell you that it will break.

    --
    Mats
    I dont think so. as its the compiler that generates the malloc subroutine..
    so it should take care of those architecture problems
    and also its the system allocating the memory chunk and malloc routine is handling the usage of that to see how much more should it ask the next time..
    If it is non prototyped and the compiler takes care of that by considering including the required headers.. I dont think that would cause problem if compiled on the specific architecture..

  13. #13
    Registered User
    Join Date
    Oct 2007
    Posts
    47
    Thank guy, that answered all my questions.

    Thanks for the links, will be reading them tonight.

  14. #14
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by gibsosmat View Post
    its in stdlib.h

    I dont think so. as its the compiler that generates the malloc subroutine..
    so it should take care of those architecture problems
    and also its the system allocating the memory chunk and malloc routine is handling the usage of that to see how much more should it ask the next time..
    If it is non prototyped and the compiler takes care of that by considering including the required headers.. I dont think that would cause problem if compiled on the specific architecture..
    Not so. If you don't have a prototype [at least a basic "return type" declaration - arguments isn't important for the discussion here] on a system that uses different registers for different types [this applies to for exampl floating point returns in FPU registers too], then the compiler will not KNOW that the return value from malloc() is a pointer, and thus assume that it's an integer type operation and use the wrong register. How is the compiler going to know what the return type is if it's not been told - the compiler doesn't KNOW intrinsically that malloc return a pointer. For that matter, if you don't actualy need the malloc function in the C library, you could very well write another function called malloc() that does somethign completely different - the compiler should be able to compile this too.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  15. #15
    lfs addicted
    Join Date
    Nov 2007
    Posts
    49
    Just another question. From the faq:

    "...There is nothing wrong with this except in the event that stdlib.h, the header which declares malloc, is not included. If the return of malloc is cast then the error which would be flagged is hidden..."

    why doesn't the compiler give an error if I do not include stdlib.h? Shouldn't it complain about not knowing funcion "malloc"?

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. tools for finding memory leaks
    By stanlvw in forum C++ Programming
    Replies: 4
    Last Post: 04-03-2009, 12:41 PM
  2. Replies: 7
    Last Post: 02-06-2009, 12:27 PM
  3. Valgrind says I suck at memory management :)
    By carrotcake1029 in forum C Programming
    Replies: 6
    Last Post: 02-01-2009, 08:10 PM
  4. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  5. Managing shared memory lookups
    By clancyPC in forum Linux Programming
    Replies: 0
    Last Post: 10-08-2003, 05:44 AM

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