Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++’s low-level memory management routines work similarly to new and delete. For

ID: 3817724 • Letter: C

Question

C++’s low-level memory management routines work similarly to new and delete.  For regular computer programs on full size systems such as laptops and desktops, new and delete are the preferred route, as they have some capabilities for object-oriented programming and multi-threading that not available to the low-level routines.  However, the low-level routines can be useful, especially for microprocessor programming for embedded systems.

This lab may seem a bit like an exercise in drudgery (or silliness, or both).  But it gives you a little practice using malloc, calloc and free, and the low-level data transfer routines memcpy and memmove. You’ll thank me when you take the microprocessors course.

The textbook does not cover this material, so you need some references so you can go beyond what this lab explains.  One good place to find reference info is a google.  Two sites which turn up at the top of google searches and which have good detailed documentation for C++ routines are www.cppreference.com/ and www.cplusplus.com.  They both have essentially the same information, though for some reason www.cplusplus.com uses the old c header files (<stdlib.h>) instead of the newer C++ header files (<cstdlib>) in their example code for the low-level routines.

Routines you will need for this lab:

sizeof              returns the size of the thing passed to it

malloc                         allocate memory

calloc               allocate memory and clear it to all zeros

free                 return previously allocated memory to the heap, aka “free store”

memmove      move data from one location to another (dest & src can overlap)

memcpy          also moves memory (dest & src cannot overlap)

memset          sets a block of bytes to all the same 8-bit values

Part 1.  Find documentation and Read about each function

a.     Look up malloc, calloc and free online.  Write in a text file or Word document and briefly explain the difference between malloc and calloc.

b.     Explain how malloc and calloc differ from new, and how calling delete and free are different.

c.     Look up memmove and memcpy, and explain the difference between them.

d.     Note the order of parameters for memmove and memcpy, then write 5 times, “I will remember that destination comes first, source comes second!”.  (Don’t bother to ask me why I think this is important to keep straight…)

e.     Briefly explain what memset does.

f.      Look up the sizeof( ) function, and explain what it does.

g.     Include the URL of the website(s) you used to learn about the various routines.

Part 2. Write a program to dynamically allocate a couple of arrays using malloc and calloc and see what they contain:

a.     Allocate an array of integers 5 elements long using calloc.

a.     Remember that calloc takes 2 parameters, the number of elements and the size (in bytes) for each element

b.     You may need to reinterpret_cast<int *>(calloc(…)) the call to calloc if your compiler doesn’t like assigning the void * address returned by calloc to an int * pointer.

b.     Set the 3rd element of the array to 259.  (That’s 256 + 3…what is it in binary?)

c.     Print the contents of the array to verify that they have been initialized to zeros (except for the 3rd element, which you just changed).

d.     Allocate an array of doubles 10 elements long using malloc.

a.     Be sure to allocate enough bytes!  Remember that you tell malloc how many bytes you need, not how many elements.

e.     Set the 3rd element of the array to 259.0 .

f.      Set the 4th element of the array to 259.875 .

g.     Print out the contents of the array, to see if they have been initialized or not

a.     (You may still get zeros…unused memory often contains zero’s, but there’s no guarantee with malloc)

h.     return the memory for both arrays to free-store using free(…)

Name your program simple_malloc_calloc_free.cpp

Part 3.  Write a program to dynamically allocate some char buffers, use memset to fill them, and use memcpy and memmove to move the data around.

I suggest you do part 3a, test and verify it’s working as expected, then add part b, test & verify, then do part 3c.  You only need to turn in the complete program, but doing it in steps will help both with understanding and if you have bugs along the way.

Part 3a.

a.     Allocate 2 char buffers of 128 bytes each using malloc.  Call your pointers thing1 and thing2 (in memory of Dr. Seuss, of course!)

b.     Initialize all 128 bytes of thing1 to asterisks (‘*’) using memset.

c.     Set the 21st  byte to a null char (‘’).  This will make the buffer contain a c-string of 20 asterisks (and terminated by the null char).

     thing1[20] = ‘’;   // this will do it!  
     memset(thing1+20, 0, 1); // this will also do it (why?)

d.     Use memset to set bytes 22-25 of  thing1 to percent signs.

e.     Print thing1  to the console using cout.  You should get only a string of 20 asterisks.

f.      Set the 42nd byte to a null char, and then
     cout << (thing1+22) << endl;
You should get your percent signs, followed by some asterisks, because you created a 2nd c-string starting at byte 22.

g.     Print the numeric values of the first 50 chars;  this will show you that your array contains 20 asterisks (42), a null char (0)  flagging the end of the c-string, 4 percent signs (37) and more asterisks.

Part 3b.

a.      Set all 128 bytes of the 2nd buffer (thing2) to dollar signs, and set the 16th byte to a null char, to create a 15-char c-string of dollar signs.

b.     Print the thing2 c-string out.

c.     Use memcpy to copy the first 5 bytes of thing1 into bytes 8-12 of thing2.

a.     Remember that memcpy and memmove’s parameters are (dest, src, count)

b.     i.e., destination is 1st parameter, source is 2nd parameter.

d.     Print thing2 again… if all goes well you’ll get some asterisks in the middle of your dollar signs.

Part 3c.  use memmove to shift the data around in thing1 and thing2 :

a.      Use memmove to move bytes 15-25 of thing1 8 bytes to the left, then print out the cstring in thing1.  If all goes well, you should end up with a shorter c-string, because it moved the bytes with the c-string-termininating null-char over.

b.     Print the numeric values of the first 50 bytes again to see if it did indeed move the bytes over for you.

c.     Use memmove to move the first 20 bytes of thing2 10 chars to the right, and print out the resulting thing2.

d.     Print the numeric values of the 1st 50 chars of thing2 to see if memmove was smart enough to move the data without overwriting.

a.     (if you used memcpy instead of memmove, what would have happened?)

e.     Did you get what you expected?

Name your program memmove_memcpy_memset.cpp

What to Turn In:

1.     your part 1 text file describing the functions

2.     simple_malloc_calloc_free.cpp

3.     memmove_memcpy_memset.cpp

C++'s low-level memory management routines work similarly to new and delete. For regular computer programs on full size systems such as laptops and desktops, new and delete are the preferred route, as they have some capabilities for object-oriented programming and mult microprocessor programming for embedded systems eading that not avai ble to the low-level routines However, the low-level routines can be use his lab may se a bet like drudgery silliness, or both a little p e low-level dat But Processars ral The textbook does not coverthis material, so you need some references so you can go beyond what this lab explains. One good place to 1nd reference info is a google. Two sites which turn up at the top of google searches and which have good detailed documentation for C++ routines are www.copreference.com/ and www.spluspluseom. They both have essentially the same information though for some reason m uses the old der files stdlib.h instead of the newer c++ header ties (ces ib in their example code for the low- Routines you will need for th returns the size of the thing passed to it size ocate memory and de tto all zeros free return previously allocated memory to the heap, aka "free store" move d o another (dest & src can overlap ry ldest & sets a block of bytes to me 8-bit valu memset Part 1 nd documentation and Read about each fur tton e online. Write in a text tie or Word document and briefly explain the diference between m a. Look up and and b. Expl nd h g del the differ d, Note the order of parameters fo memmove and memopy, write 5 times, I wi emember that destination comes first, source comes second Don't bother o ask me whylthink this is mportant to keep e, Briefly explain what memset does function, and n whi does ook up the g. Include the URL of the website(s) you used to learn about the various routines. to dyn what they cant progra a. Allocate an array of integers 5 elements long using c a. Remember that calloctakes 2 parameters, the number of elements and the size (in bytes) for each element b. You may he call to the void address retu d by Set the 3 ay to 259. (That's 256+3..wh c. Print the contents of the array to verify that they have been initialized to zeros (except for the 3rd element, which you just changed). d. Allocate an array of dou 0 elements long using a. Be sure to allocate enough bytes! Remember that you tell m y bytes Set the 3rd ay to 2 9.0 f. Set the 4 h ement of the array to 255,B75 of the array to see if they have been initi g. Print out the conten lized or not still get h. return the memory for both arrays to free-store using free(...) Name your program simple malloc calloc free.cpp

Explanation / Answer

Q1. Difference between malloc and calloc

malloc:
   - The name malloc stands for memory allocation.
   - malloc() takes one argument that is, number of bytes.
   - Syntax of malloc is void *malloc(size_t n);
   This returns a pointer to n bytes of UNINITIALIZED storage, or NULL if the request cannot be satisfied.
   If the space assigned by malloc() is overrun, the results are undefined.
   - malloc is faster than calloc.

calloc:
   - The name calloc stands for contiguous allocation.
   - calloc() take two arguments those are: number of blocks and size of each block.
   - Syntax of calloc is void *calloc(size_t n, size_t size);
   This allocates a contiguous block of memory large enough to hold 'n' elements of size_t bytes each.
   The allocated region is INITIALIZED to zero.
   - calloc takes little longer than malloc because of the extra step of initializing the allocated memory by zero.
   However, this difference in speed is very tiny and not recognizable.
  
Q2. Explain how malloc and calloc differ from new, and how calling delete and free are different.

   - new calls constructor, while malloc/calloc does not.
   - new is an operator while malloc/calloc is a function.
   - malloc/calloc returns void* while new returns exact data type.
       For example, int *n = new int(10); // initialization with new()
   - memory allocated using malloc/calloc has to be freed using free().
   - memory allocated using new has to be freed using delete operator.
   - The new keyword is also more type safe whereas malloc/calloc is not typesafe at all.
  
Q3. Look up memmove and memcpy, and explain the difference between them.

   - The memcpy function is used to copy a block of data from a source address to a destination address.
   - Syntax of memcpy() is void * memcpy(void * destination, const void * source, size_t n);
   - memmove() is similar to memcpy() as it also copies data from a source to destination.
   memcpy() leads to problems when source and destination addresses overlap as memcpy()
   simply copies data one by one from one location to another.
   - Syntax of memmove() is - void *memmove(void *destination, const void *source, size_t n);
  
Q4. Briefly explain what memset does.
  
   - Syntax of memset() is void *memset(void *str, int c, size_t n)
   where, str -- This is a pointer to the block of memory to fill.
   c -- This is the value to be set. The value is passed as an int, but the function fills the block of memory
           using the unsigned char conversion of this value.
           n -- This is the number of bytes to be set to the value.
   This function returns a pointer to the memory area str.
  
   - memset() copies the character c (an unsigned char) to the first n characters of the string pointed to, by the argument str.
  
Q5. Look up the sizeof( ) function, and explain what it does.

   - Sizeof is a compile time unary operator which can be used to compute the size of its operand.
   The result of sizeof is of unsigned integral type which is usually denoted by size_t.
  
   - Sizeof can be applied to any data-type, including primitive types such as integer, floating-point types, compound datatypes such as Structure, union etc., or pointer types .
      

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote