Memory Allocation Flashcards
Why use dynamic memory allocation rather then just initializing like this, “ int variable[100]”
The arrays capacity might not be known till runtime, so it might be too much or to little capacity.
What is the stack?
changes size continually, out of programmers control
Can you manage the Heap? How?
Yes, referenced through pointers with the following library,
#include <stdlib.h>
void *malloc(size_t size);
void free(void * ptr);
void *calloc(size_t nmeb, size_t size);
void *realloc(void *ptr, size_t size);</stdlib.h>
In python what happens when objects are no longer referenced
garbage collection
what does malloc function do?
allocates a block of memory of specified size, from the heap, its uninitialized.
if memory cant be allocated with malloc, what is returned?
NULL (the null pointer value)
what does malloc return?
returns a pointer to the allocated block.
what does the free() function do?
deallocates the block of memory pointed to by ptr.
when will free() work?
only if the ptr is a pointer previously retuned by malloc
when will free do nothing?
when the pointer you are freeing is NULL
What are the objectives of the lecture on memory allocation?
The objectives include understanding the limitations of automatic memory allocation, explaining how program data is stored in computer memory, reviewing memory management in Python, and introducing C functions to handle dynamic memory.
In imperative programming languages, where are a function’s parameters and local variables typically allocated?
They are allocated in an activation frame, which is automatically created when the function is called and deallocated when the function returns.
How is memory allocated for local variables in Python?
In Python, a local variable is allocated the first time its name is bound to an object.
In C, when are parameters and local variables allocated?
Parameters and local variables whose scope is the entire function are allocated when the function is called.
What are automatic variables in the context of memory allocation?
Automatic variables are local variables in functions that are allocated and deallocated automatically when the function is called and returns, respectively.