Thread: Memory management - How/why/when

Hybrid View

Previous Post Previous Post   Next Post Next Post
  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
    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?

  5. #5
    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

  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
    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

  9. #9
    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

  10. #10
    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.

  11. #11
    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..

  12. #12
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,665
    > 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.

  13. #13
    lfs addicted
    Join Date
    Nov 2007
    Posts
    49
    I tryed quickly and it seems that if I do not include stdlib.h I get:

    prova.c: In function 'main':
    prova.c:7: warning: incompatible implicit declaration of built-in function 'malloc'

    both with and without casting

  14. #14
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,665
    @sloppy
    Which compiler, and what command line did you use?

    > but the problem is that malloc only used only one argument that we provided.
    > the next stack entry is still there and that will mess up the remaining of the stack..
    In C, it is the caller's responsibility to clean up the space used by parameters. The caller will know two values were pushed, and therefore knows to pop off two values.

    > Still if I make my own malloc and call it in my program without prototyping
    > and in the end if I link it with the libc malloc.. that should work and malloc code will be generated.
    Only if you ignore what matsp wrote in post 11.
    The real malloc returns a pointer, but in the absence of any prototype your code will think malloc will return an int. Even if you assume that the same register is used, you're also assuming that int and pointer have the same size.
    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.

  15. #15
    lfs addicted
    Join Date
    Nov 2007
    Posts
    49
    @Salem
    I use gcc4 under linux (command line bash... does it depend on command line?)

    @gibsosmat
    it seems to me that the error doesn't come for built-in funcions even if I do not cast. but maybe it depends on my compiler...


    PS:
    Using "gcc -S" vs "g++ -S" to get assembly output of a custom malloc(int,int) functions it seems that gcc calls malloc, whereas g++ renames the custom malloc and calls the custom malloc.

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, 11:41 AM
  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, 04:44 AM