Lecture 9 Memory Allocation: Stack vs Heap
41 Questions
0 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

Which memory segment is also known as the 'free store'?

  • Data Segment
  • BSS Segment
  • Heap Segment (correct)
  • Code Segment

The code segment typically contains read-only executable instructions.

True (A)

What is a LIFO data structure?

Last-In, First-Out

The _________ segment contains uninitialized global and static variables.

<p>BSS</p> Signup and view all the answers

Match the memory allocation type with its description:

<p>Static memory allocation = Allocated once at compile time and persists throughout the program's life. Automatic memory allocation = Allocated for local variables and function parameters when the code block is entered and freed when exited. Dynamic memory allocation = Requested when needed and must be explicitly freed when no longer required.</p> Signup and view all the answers

Which of the following is a characteristic of static memory allocation in C++?

<p>The size of the variable must be known at compile time. (D)</p> Signup and view all the answers

Static variables are allocated on the stack.

<p>False (B)</p> Signup and view all the answers

What is the primary function of the call stack?

<p>Keep track of active functions</p> Signup and view all the answers

When a function is called, a ______ ______ is created and pushed onto the stack.

<p>stack frame</p> Signup and view all the answers

Match the stack operation with its description:

<p>push() = Adds an element to the top of the stack. pop() = Removes the element from the top of the stack. peek() / top() = Views the element at the top of the stack without removing it.</p> Signup and view all the answers

What is a key advantage of using the stack for memory allocation?

<p>Memory allocation and deallocation are handled automatically. (B)</p> Signup and view all the answers

Variables stored on the stack can be resized during runtime.

<p>False (B)</p> Signup and view all the answers

What does a stack pointer register track?

<p>Top of the stack</p> Signup and view all the answers

The heap is managed by the ______.

<p>Operating System</p> Signup and view all the answers

Match the memory function with its description:

<p>malloc = Allocates memory without initializing it. calloc = Allocates memory and initializes it to zero. realloc = Resizes previously allocated memory. free = Frees the allocated memory.</p> Signup and view all the answers

What is a potential problem when allocating a very large block on the heap?

<p>Heap fragmentation (C)</p> Signup and view all the answers

Memory allocated on the heap must be explicitly deallocated by the program.

<p>True (A)</p> Signup and view all the answers

What is the purpose of memset()?

<p>Fill memory with a specific value</p> Signup and view all the answers

The ___________ function copies memory from one block to another.

<p>memcpy</p> Signup and view all the answers

Match the function with its proper use case:

<p>strdup = Duplicates strings. free = Deallocates allocated memory. malloc = Allocates memory dynamically</p> Signup and view all the answers

Which function allocates memory and initializes it to zero in a single step?

<p>calloc() (B)</p> Signup and view all the answers

It’s acceptable for a C program to never call free() to deallocate memory.

<p>False (B)</p> Signup and view all the answers

What happens if a pointer to allocated memory is lost and can no longer be referenced?

<p>Memory Leak</p> Signup and view all the answers

Failing to check the return value of malloc() can lead to a ________ ______ if the allocation fails.

<p>Null Pointer</p> Signup and view all the answers

Match the description of common issues with C/C++ memory operations:

<p>Memory Leak = Memory is allocated but never freed. Segmentation Fault = Attempting to access memory the program does not have rights to. Heap Fragmentation = Free memory is broken into small blocks which are not contiguous.</p> Signup and view all the answers

Suppose you have a dynamically allocated array using malloc(). Which function should you use to increase its size?

<p>realloc() (D)</p> Signup and view all the answers

It is safe to access memory after it has been freed using free().

<p>False (B)</p> Signup and view all the answers

What is heap fragmentation and why is it a problem?

<p>Non-contiguous free blocks; prevents allocation</p> Signup and view all the answers

The _______ is automatically adjusted each time a value is pushed onto or popped from the stack.

<p>stack pointer</p> Signup and view all the answers

Where are static variables stored if they are uninitialized?

<p>BSS Segment (D)</p> Signup and view all the answers

Stack operations are slower than heap operations.

<p>False (B)</p> Signup and view all the answers

What does LIFO stand for?

<p>Last In First Out</p> Signup and view all the answers

Variables allocated automatic memory will be freed when the relevant code block is _________.

<p>exited</p> Signup and view all the answers

Why is it generally bad practice to allocate large arrays on the stack?

<p>Stack memory is limited (B)</p> Signup and view all the answers

The call stack primarily keeps track of inactive functions.

<p>False (B)</p> Signup and view all the answers

What does a program do once the function terminates?

<p>Resumes at return address</p> Signup and view all the answers

The BSS segment is also known as ___________ data.

<p>uninitialized</p> Signup and view all the answers

What is the danger of returning *ptrA in given code? TestClass *ptrA = &objTC;

<p>Dangling Pointer (D)</p> Signup and view all the answers

You can initialize global variables inside the header file.

<p>False (B)</p> Signup and view all the answers

If an allocation fails, what will malloc return?

<p>null</p> Signup and view all the answers

Make sure you __________ memory allocated dynamically.

<p>initialize</p> Signup and view all the answers

Flashcards

Code Segment

A memory area also known as the text segment.

BSS Segment

A memory area also known as uninitialized data.

Data Segment

A memory area adjacent to the BSS segment.

Heap Segment

A memory area also called the free store.

Signup and view all the flashcards

Call Stack

Also known as a stack, LIFO structure.

Signup and view all the flashcards

Static Memory Allocation

Memory allocated for static and global variables.

Signup and view all the flashcards

Automatic Memory Allocation

Memory allocated for local variables and function parameters.

Signup and view all the flashcards

Dynamic Memory Allocation

Memory requested when needed and must be freed when not needed.

Signup and view all the flashcards

LIFO Structure

A LIFO (Last-In, First-Out) data structure.

Signup and view all the flashcards

Stack Frame

A data structure holding function-call-related info.

Signup and view all the flashcards

Stack Advantages

Stack advantages include fast operations and automatic management.

Signup and view all the flashcards

Stack Disadvantages

Stack disadvantages include small size and LIFO access.

Signup and view all the flashcards

Heap

Managed by the OS, variables are allocated as required.

Signup and view all the flashcards

Heap Fragmentation

Breaking up memory into non-continuous blocks.

Signup and view all the flashcards

malloc

Allocates memory without initializing it.

Signup and view all the flashcards

calloc

Allocates memory and initializes it to 0.

Signup and view all the flashcards

realloc

Resizes previously allocated memory.

Signup and view all the flashcards

memset

Fills memory with a specific value.

Signup and view all the flashcards

memcpy

Copies memory from one block to another.

Signup and view all the flashcards

strdup

Duplicates a string, including the null terminator.

Signup and view all the flashcards

free

Frees the allocated memory.

Signup and view all the flashcards

void free(void * ptr)

Points to allocated memory/returns it to the heap.

Signup and view all the flashcards

void *malloc(int size)

Returns the allocated memory or NULL if allocation failed.

Signup and view all the flashcards

C Commandments

A set of rules to follow when writing C programs.

Signup and view all the flashcards

Closest Points

Finding the two coordinates that are nearest to each other.

Signup and view all the flashcards

Study Notes

  • The lecture covers memory allocation strategies, focusing on the stack versus the heap

Program Memory Segments

  • Code Segment: Also known as the text segment, contains program's executable instructions, and is read-only
  • BSS Segment: Contains all uninitialized (or initialized to 0) global and static variables
  • Data Segment: Adjacent to the BSS, it contains initialized static variables, size determined by data types in source code, and doesn't change at runtime
  • Heap Segment: Also called the free store, for dynamically allocated variables
  • Call Stack: Simply called stack which is a LIFO structure that tracks function calls

Call Stack Details

  • A stack pointer register tracks the top of the stack, adjusting as values are pushed or popped
  • Function parameters, local variables, and related information are stored here

Memory Allocation Types in C++

  • Static Memory Allocation: For static and global variables, allocated once at program start and persists throughout life
  • Automatic Memory Allocation: For local variables and function parameters; allocated upon code block entry and freed upon exit
  • Dynamic Memory Allocation: Used when memory is needed, and the memory must be explicitly freed when done

Static vs Automatic Allocation

  • Size of variable/array must be known at compile time
  • Memory allocation and deallocation is automatic

Static vs Automatic Variables

  • Static variables are allocated in BSS (uninitialized) or Data Segment (initialized) and is not on the stack
  • Automatic variables are allocated on the stack and persist only during a single function call

The Call Stack

  • Call stack keeps track of active functions, allocating function parameters and local variables, implemented as a container with peek(), top(), pop() and push()
  • A stack frame stores function call data and a stack pointer tracks the top of the call stack

The Call Stack's Operation

  • When program encounters a function call, a stack frame containing the return address, function arguments, local variables, and register values gets pushed onto the stack
  • The CPU jumps to the function's start point
  • Upon function termination, registers are restored, the stack frame is removed (freeing memory), and the CPU resumes execution at the return address

Advantages and Disadvantages of the Call Stack

  • Advantages: Fast stack operations, memory size known at compile time, automatic memory management, contiguous memory
  • Disadvantages: Relatively small size (typically 1MB on Windows, up to 8MB on Linux), may waste allocated memory, variables cannot be resized, LIFO access only

The Heap

  • Heap is a larger memory pool managed by the OS
  • Heap Memory is dynamically allocated to variables that returns to the OS once the program is done using it
  • The program is responsible for allocation/deallocation by creating blocks of suitable size, and can fail if blocks are not of a large enough size (heap fragmentation)

Common Memory Allocation Functions

  • malloc: Allocates memory without initializing
  • calloc: Allocates memory and initializes to 0
  • realloc: Resizes previously allocated memory
  • memset: Fills memory with value
  • memcpy: Copies memory block to another
  • strdup: Duplicates a string with null-termination
  • free: Frees allocated memory

Memory Management Details

  • void free(void * ptr): Takes a pointer to allocated memory and returns it to the heap
  • Once memory is freed, it should not be accessed unless reallocated, and undefined behavior results otherwise
  • Important:* When a program ends, its memory is completely freed
  • Uncommon for some programs to never free memory while running in general
  • Use calloc() to allocate and initialize in one go.

malloc Details.

  • void *malloc(int size): Takes a positive integer and returns a pointer if successful, or NULL if not
  • The memory is uninitialized and contains anything
  • It is good practice to initialize the memory to all zeros, using memset()

Proper C Coding Rules

  • Do not put variable definitions in header files because the same code will appear in multiple code files, cauing the linker to complain of multiple definitions of the same symbol.
  • Every code file, except the one containing main() should have a corresponding header file.
  • All functions and variables that are used outside of a code file should be declared (not defined) in the corresponding header file.
  • Initialize all variables, particularly pointers. Do not utilize global variables unless required by an API.
  • Confirm the malloc() return value
  • Initialize memory following allocation.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

Description

Explore memory allocation strategies with a focus on the stack and heap. Covers program memory segments like code, BSS, and data. Details the call stack's role in tracking function calls and dives into static memory allocation in C++.

More Like This

Memory Allocation and Fragmentation Quiz
10 questions
Memory Management: Stack Allocation
10 questions
12: Memory Management
78 questions
Use Quizgecko on...
Browser
Browser