55_pdfsam_cs2022

55_pdfsam_cs2022 - Local variables Recall that local...

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

View Full Document Right Arrow Icon
Local variables Recall that local variables are stored on the stack Memory for local variables is deallocated when function returns Returning a pointer to a local variable is almost always a bug! C requires that the size of variables on the stack be known at compile time, so dynamically-sized arrays aren’t possible char *my_strcat(char *s1, char *s2) { char s3[1024]; strcpy(s3, s1); strcat(s3, s2); return s3; // BUG! returns a pointer to a // deallocated memory region. }
Background image of page 1

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

View Full DocumentRight Arrow Icon
The Heap C can use space in another part of memory: the heap The heap is separate from the execution stack Heap regions are not deallocated when a function returns Note: this is completely unrelated to the Heap data structure The programmer requests storage space on the heap C never puts variables on the heap automatically But local variables might point to locations on the heap Heap space must be explicitly allocated and deallocated by the programmer
Background image of page 2
malloc Library function in stdlib.h
Background image of page 3

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

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

This note was uploaded on 01/10/2010 for the course CS 2022 at Cornell.

Page1 / 6

55_pdfsam_cs2022 - Local variables Recall that local...

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

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