100
c m y k
march 2008 | LINUX For YoU | www.
openITis.
com
A
ssume that you are writing code to implement a text
editor in C.
To represent characters typed in the
editor, you plan to use dynamic memory allocation
for each character.
In the following code...
More
100
c m y k
march 2008 | LINUX For YoU | www.
openITis.
com
A
ssume that you are writing code to implement a text
editor in C.
To represent characters typed in the
editor, you plan to use dynamic memory allocation
for each character.
In the following code segment, text is
a two-dimensional array of ‘char*’s.
When the user types
a character, say ‘a’, in row_pos, column_pos, memory
is dynamically allocated only for sizeof(char) and the
character is stored as in:
text[row_pos][column_pos] = malloc(sizeof(char));
*text[row_pos][column_pos] = ‘a’;
Is this an efficient approach to store characters that are
typed in the text editor?
In this approach, there are many problems in the
assumptions made for storing characters in a text
editor.
Let me point out a very significant problem.
The
sizeof(char) is 1.
But malloc(1) does not return a memory
block of size 1 byte.
Why? For that we need to understand
how dynamic memory allocation works.
Generally, in C, dynamic memory allocation
Less