Function calls takes up memory

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • KimPiX
    New Member
    • Apr 2008
    • 1

    Function calls takes up memory

    Hi,

    I am writing a c++ program for a microprocessor, and I encountered a weird problem.

    I have a simple function, which does nothing else than swapping around some bytes in a 32bit integer, which is given as argument for the function.
    The function looks something like this:

    int swapbytes(int bts)
    {
    int swap_ret;

    bitpnt = (char*)&bts;
    swappnt = (char*)&swap_re t;

    swappnt[3] = bitpnt[0];
    ... etc...
    }

    The function works fine, but the problem is, that everytime I call this function, I can see that it takes up more memory, which must mean that the compiler makes a copy of the function each time it is called. Even though it is a very small function, it takes around 250bytes extra for each time I call it.

    An example:
    swap1 = swapbytes(0x010 20304);
    swap2 = swapbytes(0x102 03040);
    swap3 = swapbytes(0x050 60708);

    This takes up 2x250 bytes more memory, than if I just called the function 1 time.

    I am using a GNU compiler.
    Is it a compiler problem, or do anyone know what I am dealing with here? ;-)

    Thanks in advance!
    Regards,
    KimPiX
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Originally posted by KimPix
    swap1 = swapbytes(0x010 20304);
    swap2 = swapbytes(0x102 03040);
    swap3 = swapbytes(0x050 60708);
    This code creates three stack frames for swapbytes. One for each call. Stack frames are invalid after the function returns, but there is no guarantee that the stack frame is deleted before the next call is made. Some compilers tend to clean up only every so often so you may have stack frames hanging around that just haven't been deleted yet.

    Check your calling convention. The default convention for C is that the caller cleans up the stack frames. That means those stack frames may not be deleted until the calling function itself is complete. Microsoft has a __stdcall convention that toggles their compiler to make the called function responsibile to delete its own stack frame upon completion. Perhaps gnu has an equivalent.

    These are the Microsoft calling conventions:
    [code=c]
    int __cdecl swap(int); /* ANS C. Caller cleans up */
    int __stdcall swap(int); /* Microsoft. Callee cleans up */
    [/code]

    The Microsoft __cdecl does not need to be part of the funcition prototype but the __stdcall does. In their world, __stdcall has been defined as WINAPI to make it stand out as Microsoft specific.

    In any case, I guarantee that in C copies of the function are not being made.

    Comment

    Working...