Thread: Memory allocation question

  1. #1
    Registered User
    Join Date
    May 2011
    Posts
    66

    Memory allocation question

    Hi.

    I was reading some articles about static and dynamic memory allocation and there is something I don`t understand.

    As I read, in assembly is it possible to extend the space used on the stack by incrementing the stack pointer. So why in C every statically allocated variable must have its size explicitly defined when writing the program, and it cannot change during execution?

    Let`s say, I need an array, but I don`t know its size from the beginning. In this case I have to declare a pointer, allocate memory for it on the heap with malloc() and as the array`s size grows, call realloc(). Why can`t I declare an array statically on the stack like int array[100] and if needed, change its size to 101 and push the next value on the stack?


    I don`t have any experience in assembly, so please excuse me, if I said something stupid.

    Thank you.
    Last edited by raczzoli; 01-07-2013 at 04:27 PM.

  2. #2
    Stoned Witch Barney McGrew's Avatar
    Join Date
    Oct 2012
    Location
    astaylea
    Posts
    420
    Quote Originally Posted by raczzoli View Post
    So why in C every statically allocated variable must have its size explicitly defined when writing the program, and it cannot change during execution?
    You're confusing static storage duration with automatic storage duration here. It's true that objects with static storage duration may only be defined with a fixed size. Array objects with automatic storage duration, however, may be defined with a variable size on implementations that support variable length arrays.

    Quote Originally Posted by raczzoli View Post
    Why can`t I declare an array statically on the stack like int array[100] and if needed, change its size to 101 and push the next value on the stack?
    C doesn't have a stack.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory allocation question
    By raczzoli in forum C Programming
    Replies: 13
    Last Post: 09-12-2012, 07:46 AM
  2. A question about memory allocation in Linux
    By BBH in forum C++ Programming
    Replies: 2
    Last Post: 08-25-2009, 06:34 PM
  3. Memory allocation question
    By dakarn in forum C Programming
    Replies: 11
    Last Post: 12-01-2008, 11:41 PM
  4. Another Question...memory allocation
    By quickclick330 in forum C Programming
    Replies: 4
    Last Post: 12-12-2007, 04:25 PM
  5. Question about memory/allocation/pointers
    By Magos in forum C++ Programming
    Replies: 4
    Last Post: 11-21-2001, 09:57 AM