csc1254lect04

csc1254lect04 - CSc 1254: Lecture # 4 Dynamic Memory...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: CSc 1254: Lecture # 4 Dynamic Memory Allocation and Type Casting August 31, 2005 Dynamic Allocation Type Casting Scope of Variables More on C 1 Dynamic Allocation There are three ways to allocate memory for variables. You are probably already familiar with two ways: static and automatic allocation. When a global variable is declared, the compiler allocates a fixed location in memory for the variable that persists throughout the entire program. This is called static allocation . By the way, stay away from using global variables they may create unintended side effects. On the other hand, when a local variable is declared, memory for that variable is allocated on the system stack and when the function returns the memory is deallocated (freed). This is called automatic allocation . The problem with these allocation styles, especially when dealing with arrays, is that we must decide in advance the size of the array. For example, when dealing with strings, we often allocate some maximum length and hope that it is long enough to store the users input! The third way of allocating memory is called dynamic allocation . It allows you to allocate and explicitly deallocate memory as needed while the program is running. This comes from unallocated memory. In this allocation you specify how many bytes of memory you need for the variable. This pool of unallocated memory is called the heap . 1 A common pitfall when using pointers is to forget to allocate memory for them. Remember, a pointer holds an address in memory. Simply declaring a pointer does not mean that it points to memory that has been allocated....
View Full Document

Page1 / 6

csc1254lect04 - CSc 1254: Lecture # 4 Dynamic Memory...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online