using malloc in a function

This is a discussion on using malloc in a function within the C Programming forums, part of the General Programming Boards category; i have a question about using malloc to assign variable memory. So if i use malloc i should free that ...

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    16

    using malloc in a function

    i have a question about using malloc to assign variable memory.
    So if i use malloc i should free that pointer after i use it right.

    How about it in a function i use malloc to allocate memory for a local variable.......but i call that function say 100 times. Should I also have a free before the end of that function? Also would it be more efficient to just declare it once as a global variable? (does the function redeclare all the variables each time it is called?)

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Quote Originally Posted by cuizy View Post
    i have a question about using malloc to assign variable memory.
    So if i use malloc i should free that pointer after i use it right.

    How about it in a function i use malloc to allocate memory for a local variable.......but i call that function say 100 times. Should I also have a free before the end of that function? Also would it be more efficient to just declare it once as a global variable? (does the function redeclare all the variables each time it is called?)
    That depends entirely on what you (are attempting to) do. You should not be using malloc to create a local variable, ever (mostly). Your function should be using malloc to create objects that will last longer than the lifespan of the function, and those objects should be freed when they are no longer needed.

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    The answer to your question is "it depends".

    A global variable is GENERALLY a bad idea. It causes unnecessary connections between function calls that MAY not need to be connected.

    The better option would be to either pass the variable along from the calling function, or simply not use dynamic allocation at all.

    If you have a modern OS (such as Windows or Linux), and this function isn't recursive or some such, then having a fairly large stack allocation in one function isn't such a bad idea. And that takes no/very little overhead in the function. Compared to a call to malloc/free, it's probably 30-50 times faster. So that's another option.

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

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by cuizy View Post
    1) Should I also have a free before the end of that function? 2) Also would it be more efficient to just declare it once as a global variable? 3) (does the function redeclare all the variables each time it is called?)
    1) Yes, presuming the variable is not used outside of the function. malloc'ing a variable in this way is quite unusual, however: why do you want/need to?

    2) In theory yes, since you would save those fresh malloc calls every time, but generally this "optimization" would be irrelevant. You should restrict the number of globals in use, so in other words, it would be a bad rule to just make all such variables global ESPECIALLY if they are used in only one function -- that is a almost always a no-no.

    3) Every time a function is called a new stack is created for it (but malloc'd variables don't go there, they go on the heap).

    Mostly malloc'd "heap" variables are used because they are being passed out for use in another function. You should explain further what exactly you are thinking of doing and someone will comment more specifically on the wisdom of your idea.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  5. #5
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    Location
    in front of my computer
    Posts
    804
    >>Every time a function is called a new stack is created for it
    Isn't this wrong? I think there is a single stack for the whole program(which includes several functions and all that), whenever we call a function all the temp variables and return addresses are pushed in the same stack. Or is it that a whole new stack is created exclusively for that function and all the return addresses and temp variables are stored in it. Please explain it a bit.
    HOPE YOU UNDERSTAND.......

    By associating with wise people you will become wise yourself
    It's fine to celebrate success but it is more important to heed the lessons of failure
    We've got to put a lot of money into changing behavior


    PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
    IDE- Microsoft Visual Studio 2008 Express Edition

  6. #6
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by BEN10 View Post
    Isn't this wrong? I think there is a single stack for the whole program(which includes several functions and all that), whenever we call a function all the temp variables and return addresses are pushed in the same stack.
    I think you are right; the term I should have used is stack frame (as in "a new stack frame is created" for each function). I was just trying to distinguish stack variables, which would tend by nature to be more short lived, from heap variables.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  7. #7
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,246
    >> Isn't this wrong? I think there is a single stack for the whole program(which includes several functions and all that)
    Actually there is 1 stack per thread, not one for the whole program.
    bit∙hub [bit-huhb] n. A source and destination for information.

  8. #8
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,047
    Quote Originally Posted by cuizy View Post
    i have a question about using malloc to assign variable memory.
    If the storage required by the variable fluctuates then you have to use dynamic storage allocation ie malloc() / free(). But if the storage required by the variable is fixed then defining a local variable is sufficient.

  9. #9
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,304
    Quote Originally Posted by cuizy View Post
    i have a question about using malloc to assign variable memory.
    So if i use malloc i should free that pointer after i use it right.

    How about it in a function i use malloc to allocate memory for a local variable.......but i call that function say 100 times. Should I also have a free before the end of that function? Also would it be more efficient to just declare it once as a global variable? (does the function redeclare all the variables each time it is called?)
    If you come to understand exactly what it does, then you should be able to deduce any answers as to how to use it on your own. Search for various sources that explain what it does and read them.

    For now you should completely forget about efficiency. You're more likely to go off doing something bazaar and stupid in your code because you heard somewhere that it was more efficient, if you worry about it now. You'll create nightmare code and hinder your learning.
    Just aim for the shortest and clearest code you can possibly write, and there's a very good chance it'll be relatively efficient.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  10. #10
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,832
    Maybe you are looking for the functionality of using 'static' variables inside a function. They retain their values from one function invocation to the next. Similar to global in allocation but their scope is local.

  11. #11
    Registered User
    Join Date
    Apr 2009
    Posts
    16
    thanks for all the suggestions,
    what i'm using it for is that I wanted to use some matrix manipulations through lapack, and if i just pass the original pointers to the matrix/vectors, some of the functions of lapack will change the values of the original matrix/vector. So i wanted to have a copy of those vectors and work with that without changing the original values. Also the matrix/vectors will have different sizes depending on each call....... so i will need to malloc each time the function is called (i guess that means i can't define it as a global variable)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM
  2. C++ compilation issues
    By Rupan in forum C++ Programming
    Replies: 1
    Last Post: 08-22-2005, 05:45 AM
  3. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  4. malloc & cover function
    By Max in forum C Programming
    Replies: 4
    Last Post: 10-04-2002, 08:51 AM
  5. qt help
    By Unregistered in forum Linux Programming
    Replies: 1
    Last Post: 04-20-2002, 09:51 AM

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