Exercises:Dynamic Memory: Difference between revisions

From COMP15212 Wiki
gravatar Yuron [userbureaucratinterface-adminsysopPHRhYmxlIGNsYXNzPSJ0d3BvcHVwIj48dHI+PHRkIGNsYXNzPSJ0d3BvcHVwLWVudHJ5dGl0bGUiPkdyb3Vwczo8L3RkPjx0ZD51c2VyPGJyIC8+YnVyZWF1Y3JhdDxiciAvPmludGVyZmFjZS1hZG1pbjxiciAvPnN5c29wPGJyIC8+PC90ZD48L3RyPjwvdGFibGU+] (talk | contribs)
m (1 revision imported)
gravatar W81054ch [userbureaucratinterface-adminsysopPHRhYmxlIGNsYXNzPSJ0d3BvcHVwIj48dHI+PHRkIGNsYXNzPSJ0d3BvcHVwLWVudHJ5dGl0bGUiPkdyb3Vwczo8L3RkPjx0ZD51c2VyPGJyIC8+YnVyZWF1Y3JhdDxiciAvPmludGVyZmFjZS1hZG1pbjxiciAvPnN5c29wPGJyIC8+PC90ZD48L3RyPjwvdGFibGU+] (talk | contribs)
m (1 revision imported)
 
(One intermediate revision by one other user not shown)
Line 6: Line 6:




Sometimes, programs need to create variables at run time.  This
Sometimes, programs need to create variables at run time.  This requires a request to the operating system for more of the machine’s resources.  This request is typically contained in some language construct.  In Java (for example) it is performed by the function “new”.  In C the call is rather cruder and comes under the name “malloc” (from “memory allocate”);
requires a request to the operating system for more of the machine’s
<code>malloc()</code> will allocate the requested number of (contiguous) bytes (if there are any spare) and return a [[Pointers|<strong>pointer</strong>]] to their location.
resources.  This request is typically contained in some language
construct.  In Java (for example) it is performed by the function
“new”.  In C the call is rather cruder and comes under the
name “malloc” (from “memory allocate”);
<code>malloc()</code> will allocate the requested number of (contiguous) bytes
(if there are any spare) and return a [[Pointers|<strong>pointer</strong>]] to their location.


Example:
Example:
Line 22: Line 16:
</syntaxhighlight>
</syntaxhighlight>
<blockquote>
<blockquote>
<span style="color:red">Oops</span>: that example assumes <code>malloc()</code>
<span style="color:red">Oops</span>: that example assumes <code>malloc()</code> will be successful; if the system rejects the request (unlikely!) then a NULL will be returned and the assignment will “seg. fault”.  You can ignore the test for now, but your
will be successful; if the system rejects the request (unlikely!)
then a NULL will be returned and the assignment will
“seg. fault”.  You can ignore the test for now, but your
conscience should haunt you.
conscience should haunt you.
</blockquote>
</blockquote>
Whilst this works, it would be unusual to allocate a single integer;
Whilst this works, it would be unusual to allocate a single integer; this mechanism is usually used for larger structures.
this mechanism is usually used for larger structures.


As we have no [https://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29 garbage collection],
As we have no [https://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29 garbage collection], it is the programmer’s job to use the complementary call to dispose of the ‘litter’.
it is the programmer’s job to use the complementary call to dispose of
the ‘litter’.
<syntaxhighlight lang="C">
<syntaxhighlight lang="C">
free(p_new_int);
free(p_new_int);
</syntaxhighlight>
</syntaxhighlight>
This disposes of the memory allocated by <code>malloc()</code>. The pointer, created
This disposes of the memory allocated by <code>malloc()</code>. The pointer, created statically by the <code>int *p_new_int;</code> declaration is still there, of course. (<em>Make a sketch showing the pointer <em>and</em> the temporarily allocated item.</em>)
statically by the <code>int *p_new_int;</code> declaration is still there, of course.
(<em>Make a sketch showing the pointer <em>and</em> the temporarily allocated item.</em>)


Don’t <em>use</em> that pointer <em>value</em> again after the <code>free()</code>; it is invalid.
Don’t <em>use</em> that pointer <em>value</em> again after the <code>free()</code>; it is invalid.


Notice that <code>free()</code> used the only a pointer to identify the memory
Notice that <code>free()</code> used the only a pointer to identify the memory which was being released; this is because the system has kept track of the <strong>size</strong> of the blocks as they were allocated.  The system is also keeping track of which program ‘owns’ which memory so that, when the program terminates, all its resources can be recovered anyway. This is an operating system function and will happen regardless of whether the program finished ‘properly’ or it crashed.
which was being released; this is because the system has kept track of
the <strong>size</strong> of the blocks as they were allocated.  The system is also
keeping track of which program ‘owns’ which memory so
that, when the program terminates, all its resources can be recovered
anyway. This is an operating system function and will happen
regardless of whether the program finished ‘properly’ or
it crashed.


=== Practical ===
=== Practical ===
Compile and run <code>allocate.c</code>; look at the source code and understand
Compile and run <code>allocate.c</code>; look at the source code and understand what it is doing.  You might like to add some <code>printf()</code>s to see the allocated address, too.
what it is doing.  You might like to add some <code>printf()</code>s to see the
allocated address, too.


=== Puzzles ===
=== Puzzles ===
Line 61: Line 38:
*What happens if you don’t allocate a big enough space for your string?<br /> (Alternatively, what if your string <em>overflows</em> your allocated space?)
*What happens if you don’t allocate a big enough space for your string?<br /> (Alternatively, what if your string <em>overflows</em> your allocated space?)
*What problem (if any) might you have if you miss out the <code>free()</code> call?<br /> (You could try it but that might not show everything.)
*What problem (if any) might you have if you miss out the <code>free()</code> call?<br /> (You could try it but that might not show everything.)
----
=== Submission ===
* A text file with some <em>short</em> (i.e. one sentence each?) answers to the puzzles; if you can’t think of anything (especially for the second one) just say so.<br /> Call it: [<code>ex3.txt</code>].
----
----
{{PageGraph}}
{{PageGraph}}
{{Category|Exercises}}
{{Category|Exercises}}

Latest revision as of 10:22, 9 August 2019

On path: Exercises 0: Exercises • 1: Pointer Exercise • 2: Arguments Exercise • 3: Malloc Exercise • 4: Structs Exercise • 5: Processes Exercise • 6: Shared memory Exercise • 7: Pipes Exercise • 8: Exceptions Exercise • 9: Synchronisation Exercise • 10: Files Exercise • 11: Threads Exercise • 12: Unix proc Exercise
On path: Pointers 1: Memory • 2: Arrays • 3: Pointers • 4: Pointer Exercise • 5: Structures • 6: Dynamic Memory Allocation • 7: Malloc Exercise • 8: Structs Exercise
Depends on Dynamic Memory AllocationPointers

Download exercise files


Sometimes, programs need to create variables at run time. This requires a request to the operating system for more of the machine’s resources. This request is typically contained in some language construct. In Java (for example) it is performed by the function “new”. In C the call is rather cruder and comes under the name “malloc” (from “memory allocate”); malloc() will allocate the requested number of (contiguous) bytes (if there are any spare) and return a pointer to their location.

Example:

int *p_new_int;
p_new_int = malloc( sizeof(int) ); // Allocate an int of memory
*p_new_int = 1234;                 // Assign a value to that memory - note the dereference

Oops: that example assumes malloc() will be successful; if the system rejects the request (unlikely!) then a NULL will be returned and the assignment will “seg. fault”. You can ignore the test for now, but your conscience should haunt you.

Whilst this works, it would be unusual to allocate a single integer; this mechanism is usually used for larger structures.

As we have no garbage collection, it is the programmer’s job to use the complementary call to dispose of the ‘litter’.

free(p_new_int);

This disposes of the memory allocated by malloc(). The pointer, created statically by the int *p_new_int; declaration is still there, of course. (Make a sketch showing the pointer and the temporarily allocated item.)

Don’t use that pointer value again after the free(); it is invalid.

Notice that free() used the only a pointer to identify the memory which was being released; this is because the system has kept track of the size of the blocks as they were allocated. The system is also keeping track of which program ‘owns’ which memory so that, when the program terminates, all its resources can be recovered anyway. This is an operating system function and will happen regardless of whether the program finished ‘properly’ or it crashed.

Practical

Compile and run allocate.c; look at the source code and understand what it is doing. You might like to add some printf()s to see the allocated address, too.

Puzzles

  • What happens if you don’t allocate a big enough space for your string?
    (Alternatively, what if your string overflows your allocated space?)
  • What problem (if any) might you have if you miss out the free() call?
    (You could try it but that might not show everything.)