#1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    1
    Rep Power
    0

    C + Assembly ( n00b help )


    Hi

    Why is it that when i declare "char buffer[1]" in a fucntion, it reserves 4 bytes on the stack wheras for "char buffer[3]" it takes up 24 bytes ? ( char buffer[8] takes only 8 bytes . )

    Code:
    void function(int a) { 
    char buffer[1]; 
    } 
    main() { 
    function(1); 
    }
    root: gcc -S -o f.s f.c

    Code:
    function: 
       pushl   %ebp 
       movl   %esp, %ebp 
       subl   $4, %esp 
       leave 
       ret
    Now, if i change buffer[1] to buffer[3], then that $4 changes to $24 :confused:
    For buffer[8], $4 changes to $8

    Can someone please tell me how this actually works. From what i know, buffer[3] should take only 4 bytes.

    Thank you
    13x
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    55
    Rep Power
    12
    subl $4, %esp means move the stack pointer up 4 places, (allocate an extra memory location on the top of the stack).
    You should allocate and deallocate in multiples of 4, remember, an address on a 32bit processor/os is 4 bytes.

    In your main() assembly output it will add esp, 4 (this is intel syntax), this cleans the top position of the stack, for the 1 byte of memory you allocated for your buffer.

    I have absolutely no idea why it gives you 7 memory locations when you ask for 3 bytes.

    Hopefully someone can clarify this more.
  4. #3
  5. not a fan of fascism (n00b)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Feb 2003
    Location
    ct
    Posts
    2,756
    Rep Power
    95
    can you post where is takes away 24 please. maybe you disassembled the wrong section or something

    also you said C++ but i see your using gcc instead of g++?
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    55
    Rep Power
    12
    He didn't disassemble the wrong section, the application he pasted only need to allocate stack space (without just push'ing) for the buffer.

IMN logo majestic logo threadwatch logo seochat tools logo