SlideShare a Scribd company logo
1 of 1
Download to read offline
The Joy of
Programming
Dynamic Memory Allocation in C                                                                                       S.G. GaneSh
In this column, let us try to understand the nitty-gritty of dynamic allocation
using a few programming problems.



A
        ssume that you are writing code to implement a text         So, the design to store characters in the text editor by using
        editor in C. To represent characters typed in the           malloc(sizeof(char)) is not a good idea.
        editor, you plan to use dynamic memory allocation               Now let us look at a problem in using dynamic allocation.
for each character. In the following code segment, text is          The following code is for freeing a linked list. Will it work?
a two-dimensional array of ‘char*’s. When the user types
a character, say ‘a’, in row_pos, column_pos, memory                 for(	ptr	=	head	;	ptr	!=	NULL	;	ptr	=	ptr->next	)
is dynamically allocated only for sizeof(char) and the               	       free(ptr);
character is stored as in:
                                                                        Here, in the expression ptr = ptr->next, ptr is accessed
 	       text[row_pos][column_pos]	=	malloc(sizeof(char));	         after ptr is released using function free. This also serves as
 	       *text[row_pos][column_pos]	=	‘a’;	                         example for dangling pointers where the pointer is used even
                                                                    after freeing the block. So the behaviour of this code segment
    Is this an efficient approach to store characters that are      is undefined. However, it usually works well in practice. Why?
typed in the text editor?                                           The free function need not actually ‘release’ the memory
    In this approach, there are many problems in the                immediately after the call to free it. Usually, C implementations
assumptions made for storing characters in a text                   implement ‘free’ by moving a memory block to a ‘free list’
editor. Let me point out a very significant problem. The            without modifying the contents in the block. So, this code will
sizeof(char) is 1. But malloc(1) does not return a memory           work fine in many of the implementations. However, it is not
block of size 1 byte. Why? For that we need to understand           recommended to write code like this with such implementation
how dynamic memory allocation works.                                defined behaviour. For this problem, there is a simple
    Generally, in C, dynamic memory allocation is                   solution—introduce a temporary variable as in:
implemented using a linked list mechanism to allocate
memory blocks of different sizes. So, for each block                 for(	ptr	=	head	;	ptr	!=	NULL	;	ptr	=	temp)	{
allocated, it has to remember the size of the allocated              temp	=	ptr->next;
block (so that it can be subsequently freed). Remember               free(ptr);
that malloc returns a void *. Since malloc does not know             }
the type to which the returned block will be cast and
used, it has to allocate a block that is within the maximum             The implementation for dynamic allocation outlined here
alignment requirements imposed by a platform. Typically,            uses a straightforward, simple implementation. However,
this is 4 to 8 bytes. In addition, since dynamic memory             real-world implementations are obviously more complex. For
allocation is implemented using (usually) a singly linked list,     example, few C implementations provide a user directed Small
at least one pointer to the next block needs to be stored. So,      Block Allocator (SBA) mechanism so that the programmers can
allocation of a block requires at least these fields:               tune the C dynamic memory allocator implementation for small
l	 Space to store information about the ‘size’ of the fragment      block allocation. In Linux implementations (for example, glibc),
l	 The actual memory of length ‘size’ bytes (within                 the mmap system call is used to allocate large memory blocks
     maximum alignment requirements)                                (segments) with malloc. In this approach, when free is called,
l	 The pointer to the next free block                               the large blocks (segments) can be returned to the system.
    So, for example, if the maximum alignment requirement               There are lots of resources available on the Web about
is 8 bytes, and an integer of 4 bytes is used to store the          interesting implementation details—http://en.wikipedia.
size of the requested block and the pointer size is 4 bytes         org/wiki/Malloc is a good place to start.
(which is used to store the next pointer), malloc has to
return a block with minimum 16 bytes for a call. In some              S.G. Ganesh is a research engineer at Siemens (Corporate
other unusual implementation, if the maximum alignment                Technology). His latest book is “60 Tips on Object Oriented
requirement is 16, and if sizeof int and pointers are 8, it will      Programming”, published by Tata McGraw-Hill in December
                                                                      last year. You can reach him at sgganesh@gmail.com.
require a minimum of 32 bytes for allocating a single block!


100    march 2008   |   LINUX For YoU   |   www.openITis.com



                                                                   cmyk

More Related Content

What's hot

Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...
Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...
Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...Mangalayatan university
 
Time space trade off
Time space trade offTime space trade off
Time space trade offanisha talwar
 
Dot net parallelism and multicore computing
Dot net parallelism and multicore computingDot net parallelism and multicore computing
Dot net parallelism and multicore computingAravindhan Gnanam
 
Malloc() and calloc() in c
Malloc() and calloc() in cMalloc() and calloc() in c
Malloc() and calloc() in cMahesh Tibrewal
 
Bt0068 computer organization and architecture
Bt0068   computer organization and architectureBt0068   computer organization and architecture
Bt0068 computer organization and architecturesmumbahelp
 
4 dynamic memory allocation
4 dynamic memory allocation4 dynamic memory allocation
4 dynamic memory allocationFrijo Francis
 
DL for setence classification project presentation
DL for setence classification project presentationDL for setence classification project presentation
DL for setence classification project presentationHoàng Triều Trịnh
 
Colfax-Winograd-Summary _final (1)
Colfax-Winograd-Summary _final (1)Colfax-Winograd-Summary _final (1)
Colfax-Winograd-Summary _final (1)Sangamesh Ragate
 
Lexically constrained decoding for sequence generation using grid beam search
Lexically constrained decoding for sequence generation using grid beam searchLexically constrained decoding for sequence generation using grid beam search
Lexically constrained decoding for sequence generation using grid beam searchSatoru Katsumata
 
Aggregation computation over distributed data streams(the final version)
Aggregation computation over distributed data streams(the final version)Aggregation computation over distributed data streams(the final version)
Aggregation computation over distributed data streams(the final version)Yueshen Xu
 
AI&BigData Lab 2016. Руденко Петр: Особенности обучения, настройки и использо...
AI&BigData Lab 2016. Руденко Петр: Особенности обучения, настройки и использо...AI&BigData Lab 2016. Руденко Петр: Особенности обучения, настройки и использо...
AI&BigData Lab 2016. Руденко Петр: Особенности обучения, настройки и использо...GeeksLab Odessa
 
Dynamic Memory Allocation
Dynamic Memory AllocationDynamic Memory Allocation
Dynamic Memory Allocationvaani pathak
 
Deep Learning for Image Analysis
Deep Learning for Image AnalysisDeep Learning for Image Analysis
Deep Learning for Image AnalysisLevan Tsinadze
 
Java/Scala Lab 2016. Владимир Гарбуз: Написание безопасного кода на Java.
Java/Scala Lab 2016. Владимир Гарбуз: Написание безопасного кода на Java.Java/Scala Lab 2016. Владимир Гарбуз: Написание безопасного кода на Java.
Java/Scala Lab 2016. Владимир Гарбуз: Написание безопасного кода на Java.GeeksLab Odessa
 
How to use probabilistic inference programming for application orchestration ...
How to use probabilistic inference programming for application orchestration ...How to use probabilistic inference programming for application orchestration ...
How to use probabilistic inference programming for application orchestration ...Veselin Pizurica
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and AlgorithmDhaval Kaneria
 
Braxton McKee, CEO & Founder, Ufora at MLconf NYC - 4/15/16
Braxton McKee, CEO & Founder, Ufora at MLconf NYC - 4/15/16Braxton McKee, CEO & Founder, Ufora at MLconf NYC - 4/15/16
Braxton McKee, CEO & Founder, Ufora at MLconf NYC - 4/15/16MLconf
 
Applications of data structures
Applications of data structuresApplications of data structures
Applications of data structuresWipro
 

What's hot (20)

Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...
Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...
Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...
 
Time space trade off
Time space trade offTime space trade off
Time space trade off
 
Dot net parallelism and multicore computing
Dot net parallelism and multicore computingDot net parallelism and multicore computing
Dot net parallelism and multicore computing
 
C dynamic ppt
C dynamic pptC dynamic ppt
C dynamic ppt
 
Malloc() and calloc() in c
Malloc() and calloc() in cMalloc() and calloc() in c
Malloc() and calloc() in c
 
Bt0068 computer organization and architecture
Bt0068   computer organization and architectureBt0068   computer organization and architecture
Bt0068 computer organization and architecture
 
4 dynamic memory allocation
4 dynamic memory allocation4 dynamic memory allocation
4 dynamic memory allocation
 
DL for setence classification project presentation
DL for setence classification project presentationDL for setence classification project presentation
DL for setence classification project presentation
 
Colfax-Winograd-Summary _final (1)
Colfax-Winograd-Summary _final (1)Colfax-Winograd-Summary _final (1)
Colfax-Winograd-Summary _final (1)
 
Lexically constrained decoding for sequence generation using grid beam search
Lexically constrained decoding for sequence generation using grid beam searchLexically constrained decoding for sequence generation using grid beam search
Lexically constrained decoding for sequence generation using grid beam search
 
Aggregation computation over distributed data streams(the final version)
Aggregation computation over distributed data streams(the final version)Aggregation computation over distributed data streams(the final version)
Aggregation computation over distributed data streams(the final version)
 
AI&BigData Lab 2016. Руденко Петр: Особенности обучения, настройки и использо...
AI&BigData Lab 2016. Руденко Петр: Особенности обучения, настройки и использо...AI&BigData Lab 2016. Руденко Петр: Особенности обучения, настройки и использо...
AI&BigData Lab 2016. Руденко Петр: Особенности обучения, настройки и использо...
 
Dynamic Memory Allocation
Dynamic Memory AllocationDynamic Memory Allocation
Dynamic Memory Allocation
 
Deep Learning for Image Analysis
Deep Learning for Image AnalysisDeep Learning for Image Analysis
Deep Learning for Image Analysis
 
Java/Scala Lab 2016. Владимир Гарбуз: Написание безопасного кода на Java.
Java/Scala Lab 2016. Владимир Гарбуз: Написание безопасного кода на Java.Java/Scala Lab 2016. Владимир Гарбуз: Написание безопасного кода на Java.
Java/Scala Lab 2016. Владимир Гарбуз: Написание безопасного кода на Java.
 
How to use probabilistic inference programming for application orchestration ...
How to use probabilistic inference programming for application orchestration ...How to use probabilistic inference programming for application orchestration ...
How to use probabilistic inference programming for application orchestration ...
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and Algorithm
 
Braxton McKee, CEO & Founder, Ufora at MLconf NYC - 4/15/16
Braxton McKee, CEO & Founder, Ufora at MLconf NYC - 4/15/16Braxton McKee, CEO & Founder, Ufora at MLconf NYC - 4/15/16
Braxton McKee, CEO & Founder, Ufora at MLconf NYC - 4/15/16
 
Applications of data structures
Applications of data structuresApplications of data structures
Applications of data structures
 
Data structure
Data structureData structure
Data structure
 

Similar to 15 Jo P Mar 08

Please do ECE572 requirementECECS 472572 Final Exam Project (W.docx
Please do ECE572 requirementECECS 472572 Final Exam Project (W.docxPlease do ECE572 requirementECECS 472572 Final Exam Project (W.docx
Please do ECE572 requirementECECS 472572 Final Exam Project (W.docxARIV4
 
ECECS 472572 Final Exam ProjectRemember to check the errat.docx
ECECS 472572 Final Exam ProjectRemember to check the errat.docxECECS 472572 Final Exam ProjectRemember to check the errat.docx
ECECS 472572 Final Exam ProjectRemember to check the errat.docxtidwellveronique
 
ECECS 472572 Final Exam ProjectRemember to check the err.docx
ECECS 472572 Final Exam ProjectRemember to check the err.docxECECS 472572 Final Exam ProjectRemember to check the err.docx
ECECS 472572 Final Exam ProjectRemember to check the err.docxtidwellveronique
 
ECECS 472572 Final Exam ProjectRemember to check the errata
ECECS 472572 Final Exam ProjectRemember to check the errata ECECS 472572 Final Exam ProjectRemember to check the errata
ECECS 472572 Final Exam ProjectRemember to check the errata EvonCanales257
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocationGrishma Rajput
 
Dynamic memory Allocation in c language
Dynamic memory Allocation in c languageDynamic memory Allocation in c language
Dynamic memory Allocation in c languagekiran Patel
 
Writing Efficient Code Feb 08
Writing Efficient Code Feb 08Writing Efficient Code Feb 08
Writing Efficient Code Feb 08Ganesh Samarthyam
 
Os Reindersfinal
Os ReindersfinalOs Reindersfinal
Os Reindersfinaloscon2007
 
Os Reindersfinal
Os ReindersfinalOs Reindersfinal
Os Reindersfinaloscon2007
 
C interview questions
C interview questionsC interview questions
C interview questionsSoba Arjun
 
Article link httpiveybusinessjournal.compublicationmanaging-.docx
Article link httpiveybusinessjournal.compublicationmanaging-.docxArticle link httpiveybusinessjournal.compublicationmanaging-.docx
Article link httpiveybusinessjournal.compublicationmanaging-.docxfredharris32
 
C interview-questions-techpreparation
C interview-questions-techpreparationC interview-questions-techpreparation
C interview-questions-techpreparationKushaal Singla
 
C11/C++11 Memory model. What is it, and why?
C11/C++11 Memory model. What is it, and why?C11/C++11 Memory model. What is it, and why?
C11/C++11 Memory model. What is it, and why?Mikael Rosbacke
 
The reasons why 64-bit programs require more stack memory
The reasons why 64-bit programs require more stack memoryThe reasons why 64-bit programs require more stack memory
The reasons why 64-bit programs require more stack memoryPVS-Studio
 
Sperasoft‬ talks j point 2015
Sperasoft‬ talks j point 2015Sperasoft‬ talks j point 2015
Sperasoft‬ talks j point 2015Sperasoft
 

Similar to 15 Jo P Mar 08 (20)

Please do ECE572 requirementECECS 472572 Final Exam Project (W.docx
Please do ECE572 requirementECECS 472572 Final Exam Project (W.docxPlease do ECE572 requirementECECS 472572 Final Exam Project (W.docx
Please do ECE572 requirementECECS 472572 Final Exam Project (W.docx
 
ECECS 472572 Final Exam ProjectRemember to check the errat.docx
ECECS 472572 Final Exam ProjectRemember to check the errat.docxECECS 472572 Final Exam ProjectRemember to check the errat.docx
ECECS 472572 Final Exam ProjectRemember to check the errat.docx
 
ECECS 472572 Final Exam ProjectRemember to check the err.docx
ECECS 472572 Final Exam ProjectRemember to check the err.docxECECS 472572 Final Exam ProjectRemember to check the err.docx
ECECS 472572 Final Exam ProjectRemember to check the err.docx
 
ECECS 472572 Final Exam ProjectRemember to check the errata
ECECS 472572 Final Exam ProjectRemember to check the errata ECECS 472572 Final Exam ProjectRemember to check the errata
ECECS 472572 Final Exam ProjectRemember to check the errata
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocation
 
Dynamic Memory Allocation in C
Dynamic Memory Allocation in CDynamic Memory Allocation in C
Dynamic Memory Allocation in C
 
Dynamic memory Allocation in c language
Dynamic memory Allocation in c languageDynamic memory Allocation in c language
Dynamic memory Allocation in c language
 
Introduction to Parallelization ans performance optimization
Introduction to Parallelization ans performance optimizationIntroduction to Parallelization ans performance optimization
Introduction to Parallelization ans performance optimization
 
Writing Efficient Code Feb 08
Writing Efficient Code Feb 08Writing Efficient Code Feb 08
Writing Efficient Code Feb 08
 
Os Reindersfinal
Os ReindersfinalOs Reindersfinal
Os Reindersfinal
 
Os Reindersfinal
Os ReindersfinalOs Reindersfinal
Os Reindersfinal
 
Introduction to c part -3
Introduction to c   part -3Introduction to c   part -3
Introduction to c part -3
 
Introduction to Parallelization ans performance optimization
Introduction to Parallelization ans performance optimizationIntroduction to Parallelization ans performance optimization
Introduction to Parallelization ans performance optimization
 
C interview questions
C interview questionsC interview questions
C interview questions
 
Article link httpiveybusinessjournal.compublicationmanaging-.docx
Article link httpiveybusinessjournal.compublicationmanaging-.docxArticle link httpiveybusinessjournal.compublicationmanaging-.docx
Article link httpiveybusinessjournal.compublicationmanaging-.docx
 
C interview-questions-techpreparation
C interview-questions-techpreparationC interview-questions-techpreparation
C interview-questions-techpreparation
 
C11/C++11 Memory model. What is it, and why?
C11/C++11 Memory model. What is it, and why?C11/C++11 Memory model. What is it, and why?
C11/C++11 Memory model. What is it, and why?
 
Dma
DmaDma
Dma
 
The reasons why 64-bit programs require more stack memory
The reasons why 64-bit programs require more stack memoryThe reasons why 64-bit programs require more stack memory
The reasons why 64-bit programs require more stack memory
 
Sperasoft‬ talks j point 2015
Sperasoft‬ talks j point 2015Sperasoft‬ talks j point 2015
Sperasoft‬ talks j point 2015
 

More from Ganesh Samarthyam

Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeGanesh Samarthyam
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”Ganesh Samarthyam
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGanesh Samarthyam
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionGanesh Samarthyam
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeGanesh Samarthyam
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationGanesh Samarthyam
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterGanesh Samarthyam
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Ganesh Samarthyam
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckGanesh Samarthyam
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageGanesh Samarthyam
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Ganesh Samarthyam
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz QuestionsGanesh Samarthyam
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz QuestionsGanesh Samarthyam
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizGanesh Samarthyam
 

More from Ganesh Samarthyam (20)

Wonders of the Sea
Wonders of the SeaWonders of the Sea
Wonders of the Sea
 
Animals - for kids
Animals - for kids Animals - for kids
Animals - for kids
 
Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in Practice
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't Enough
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief Presentation
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - Poster
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship Deck
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming Language
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz Questions
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
 
Docker by Example - Quiz
Docker by Example - QuizDocker by Example - Quiz
Docker by Example - Quiz
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quiz
 

Recently uploaded

Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 

Recently uploaded (20)

Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 

15 Jo P Mar 08

  • 1. The Joy of Programming Dynamic Memory Allocation in C S.G. GaneSh In this column, let us try to understand the nitty-gritty of dynamic allocation using a few programming problems. A ssume that you are writing code to implement a text So, the design to store characters in the text editor by using editor in C. To represent characters typed in the malloc(sizeof(char)) is not a good idea. editor, you plan to use dynamic memory allocation Now let us look at a problem in using dynamic allocation. for each character. In the following code segment, text is The following code is for freeing a linked list. Will it work? a two-dimensional array of ‘char*’s. When the user types a character, say ‘a’, in row_pos, column_pos, memory for( ptr = head ; ptr != NULL ; ptr = ptr->next ) is dynamically allocated only for sizeof(char) and the free(ptr); character is stored as in: Here, in the expression ptr = ptr->next, ptr is accessed text[row_pos][column_pos] = malloc(sizeof(char)); after ptr is released using function free. This also serves as *text[row_pos][column_pos] = ‘a’; example for dangling pointers where the pointer is used even after freeing the block. So the behaviour of this code segment Is this an efficient approach to store characters that are is undefined. However, it usually works well in practice. Why? typed in the text editor? The free function need not actually ‘release’ the memory In this approach, there are many problems in the immediately after the call to free it. Usually, C implementations assumptions made for storing characters in a text implement ‘free’ by moving a memory block to a ‘free list’ editor. Let me point out a very significant problem. The without modifying the contents in the block. So, this code will sizeof(char) is 1. But malloc(1) does not return a memory work fine in many of the implementations. However, it is not block of size 1 byte. Why? For that we need to understand recommended to write code like this with such implementation how dynamic memory allocation works. defined behaviour. For this problem, there is a simple Generally, in C, dynamic memory allocation is solution—introduce a temporary variable as in: implemented using a linked list mechanism to allocate memory blocks of different sizes. So, for each block for( ptr = head ; ptr != NULL ; ptr = temp) { allocated, it has to remember the size of the allocated temp = ptr->next; block (so that it can be subsequently freed). Remember free(ptr); that malloc returns a void *. Since malloc does not know } the type to which the returned block will be cast and used, it has to allocate a block that is within the maximum The implementation for dynamic allocation outlined here alignment requirements imposed by a platform. Typically, uses a straightforward, simple implementation. However, this is 4 to 8 bytes. In addition, since dynamic memory real-world implementations are obviously more complex. For allocation is implemented using (usually) a singly linked list, example, few C implementations provide a user directed Small at least one pointer to the next block needs to be stored. So, Block Allocator (SBA) mechanism so that the programmers can allocation of a block requires at least these fields: tune the C dynamic memory allocator implementation for small l Space to store information about the ‘size’ of the fragment block allocation. In Linux implementations (for example, glibc), l The actual memory of length ‘size’ bytes (within the mmap system call is used to allocate large memory blocks maximum alignment requirements) (segments) with malloc. In this approach, when free is called, l The pointer to the next free block the large blocks (segments) can be returned to the system. So, for example, if the maximum alignment requirement There are lots of resources available on the Web about is 8 bytes, and an integer of 4 bytes is used to store the interesting implementation details—http://en.wikipedia. size of the requested block and the pointer size is 4 bytes org/wiki/Malloc is a good place to start. (which is used to store the next pointer), malloc has to return a block with minimum 16 bytes for a call. In some S.G. Ganesh is a research engineer at Siemens (Corporate other unusual implementation, if the maximum alignment Technology). His latest book is “60 Tips on Object Oriented requirement is 16, and if sizeof int and pointers are 8, it will Programming”, published by Tata McGraw-Hill in December last year. You can reach him at sgganesh@gmail.com. require a minimum of 32 bytes for allocating a single block! 100 march 2008 | LINUX For YoU | www.openITis.com cmyk