C代写:ENCM339 Allocation of Memory on the Heap

代写关于C和C++的五个小练习,对比这两种语言之间的差异。

Objective

The objective of this lab is focused on a variety of subjects from C to C++. Here is the summary of the some of the topics that are covered:

  • Dynamic allocation of memory in C
  • C structs with dynamic allocation of memory
  • Introduction to C++ reference type
  • Introduction to C++ classes

Note: some of the exercises in this lab are implemented in C and some in C++. For the exercises that you need to compile and run them, please make sure to use the correct compilation commands:

  • gcc for C programs
  • g++ for C++ programs.

Exercise A: Allocation of Memory on the Heap

This is an in-lab exercise.

Read This First

Before doing this exercise, you should review lecture notes or a C textbook to be sure you know exactly how C library function malloc works.

What to Do

Download the file lab7ExA.c and lab7ExA.h from D2L.Read these files carefully and draw a memory diagram for point one, assuming that all the calls to the library function malloc succeed.

What to Submit

Submit your diagram as part of your in-lab report.

Exercise B: C++ References

This is an In-lab exercise

Read This First

The AR notations that we use in ENCM 339 to show C++ references are different from ordinary types such as: int, double, and pointer notations. When we declare a reference we just provide an alias name for another memory space. In other words, a reference in C++ doesn’t have its own memory space; therefore we show them as a link (a line) between the reference-identifier and the actual allocated memory spaces. There are two little circles on both ends of these links. On one end there is a solid-black circle that represents the reference, and on the other end there is an open circle that represents the actual allocated memory space. Here are a few examples:

1
2
3
4
5
int a = 40;
int*p = &a;
int& ra = a; // ra is referred to integer a
int*& rp = p; // rp is referred to integer pointer p
int& rra = ra; // rra is also referred to a

Notice that all references ra, rp, and rra must be initialized with an expression that represents an actual memory space or another reference.

What To Do

Download the file lab7ExB.cpp from D2L. Then, draw an AR diagram for point one.

Note: You don’t need to compile and run this program but in case that you decided to run it, you should use the g++ command which is the command to compile C++ programs in our ICT 320 lab under the Cygwin. The executable file created will be still a.exe, by default.

g++ -Wall lab7ExB.cpp

What To Submit

Submit your diagrams as part of your in-lab report.

Exercise C: Objects on the Computer Memory

This is also an In-lab exercise

The objective of this exercise is to help you in understanding how C++ objects are shown on a memory diagram, and how a member function of a class uses the ‘this’pointer to access an object associated with a that particular call to the function. For further details please refer to your lecture notes and slides.

What to Do

Download files cplx.cpp, cplx.h, and lab7ExC.cpp from the D2L and draw AR diagrams for: point one and point two.

For this exercise also you just need draw the diagrams. However, if you want to compile and run it from command line in our ICT 320 lab, you should have all of the given files in the same directory and from that directory you should use the following command to compile and create an executable:

g++ -Wall cplx.cpp lab7ExC.cpp

Please notice that you shouldn’t have the header file name(s) in this command.

What To Submit

Submit your diagram as part of your in-lab report.

Exercise D: String Manipulation Using Dynamic Allocation in C

This is a post lab exercise.

The main objective of this exercise is to give you the opportunity to practice dynamic allocation of memory in C, for the purpose of string operations such as copying a string into another string, appending a string to the end of another string, or truncating the size of a string.

Read This First

Creating a kind of wrapper data type that encapsulates several related data is a common practice to build data structures such as vectors, string, linked list, trees in object oriented programming languages such as C++. We will discuss the proper way of applying these concepts during the lectures and possibly future labs.

In this exercise a structure type, called Lab7Text is defined that is similar to the structure given in Exercise A. This structure simply contains two pieces of related data. First one is a pointer that is supposed to point to a dynamically allocated array of characters, used as storage for a null-terminated c-string, called text. Second one is an integer number that represents the length of the stored string in the first data member (number of characters up to but excluding the ‘\0’).

Here is the definition of this structure:

1
2
3
4
typedef struct Lab7Text{
char *text;
int length;
} Lab7Text;

What To Do First

Download the files Lab7Text.c and Lab7Text.h from D2L. In the file Lab7Text.c, there are several functions as follows:

1
void create_empty_text (Lab7Text *txt);

Creates an object of Lab7Text that contains a string with one element holding only a ‘\0’ and its length is zero.

1
void set_c_string(Lab7Text *tx, const char* s);

Copies a c-string from s into the dynamically allocate space in the object that tx points to.

1
void text_append(Lab7Text *tx, const Lab7Text* tail);

Expands the length of dynamically allocated space for the c-string in tx to allow appending the c-string from the object that tail points at, to the end of the c-string inside the object that tx points at.

In this file in addition to a main function and the above-mentioned functions there are also three test-function for testing function: text_copy, text_append, and text_truncate.

Here is the first step, before your tasks starts: Compile and run the program and find out how functions set_c_string and text_append work. The function test_appending should produce an output that its first few lines and the last line are as follows.

As this output shows for each call to the function text_append or function set_c_string it tells you what is expected to be displayed, and then in the following line the actual output which is a string and its length, is displayed.

What To Do Second

Your next task in this exercise is to write the implementation of two missing function text_copy and function text_truncate, according to the given interface comments in the file Lab7Text.h. You are advised to write and test one function at a time, and once the function works with no errors, start working on the next function.

To complete this task, please take exactly the following steps:

  1. In the main function, change the conditional-compilation-directive for the call to test_copying from #if 0 to #if 1.
  2. Read carefully the function interface comment for function text_copy in the header file Lab7Text.h and write the implementation of this function.
  3. Compile and run the program and make sure the test results matches with expected output indicated by the function test_copying. Once all tests passes successfully, go to the next step
  4. Change the conditional-compilation-directive for the call to test_truncating from #if 0 to #if 1.
  5. Read carefully the function interface comment for function text_truncate and write the implementation of this function.
  6. Compile and run the program and make sure the test results matches with expected output indicated by the function test_truncating. Once all tests passes successfully, you are done with this exercise.

What To Submit

In your post-lab PDF file, include listings of the final versions of your Lab7Text.c, and a listing of the output of the final version of your program.

Exercise E: Writing a Class Definition and Its Implementation

This is a post-lab exercise

Read This First - What is a Helper Functions?

One of the important elements of good software design is the concept of code-reuse. The idea is that if any part of the code is repeatedly being used, we should wrap it into a function, and then reuse it by calling the function as many times as needed. In the past labs in this course and the previous programming course, we have seen how we can develop global function to reuse them as needed. A similar approach can be applied within a C++ class by implementing helper-functions. These are the functions that are declared as private member functions and are only available to the member functions of the class – Not available to the global functions such as main or member functions of the other classes.

If you pay close attention to the given instruction in the following “What to Do” section, you will find that there are some class member functions that need to implement almost a similar algorithm. They all need to change the value of data members of the class in more or less similar fashion. Then, it can be useful if you write one or more private helper-function, that can be called by any of the other member functions of the class, as needed.

Read This Second - Defining Class Clock

In this exercise you are going to design and implement a C++ class called, Clock that represents a 24-hour clock. This class should have three private integer data members called: hour, minute, and second. The minimum value of these data members is zero and their maximum values should be based on the following rules:

  • The values of minute, and second in the objects of class Clock cannot be less than 0 and more than 59.
  • The value of hour in the objects of class Clock cannot be less than 0 and more than 23.
  • As an example any of the following values of hour, minute, and second is acceptable for an object of class Clock (format is hours:minutes:seconds) : 00:00:59, 00:59:59, 23:59:59, 00:00:00. And, all of the following examples are unacceptable:
    • 24:00:00 (hour cannot exceed 23)
    • 00:90:00 (minute of second cannot exceed 59)
    • 23:-1:05 (none of the data members of class Clock can be negative)

Class Clock should have three constructors: A default constructor, that sets the values of the data-members hour, minute, and second to zeros.

A second constructor, that receives an integer argument in seconds, and initializes the Clock data members with the number of hour, minute, and second in this argument. For example if the argument value is 4205, the values of data members hour, minute and second should be: 1, 10, and 5 respectively. If the given argument value is negative the constructor should simply initialize the data members, all to zeros:

The third constructor receives three integer arguments and initializes the data members hour, minute, and second with the values of these arguments. If any of the following conditions are true this constructor should simply initialize the data members of the Clock object, all to zeros:

  • If the given values for second or minute are greater than 59 or less than zero.
  • If the given value for hour is greater than 23 or less than zero.

Class Clock should also provide a group of access member functions (getters, and setters) that allow the users of the class to retrieve values of each data member, or to modify the entire value of time. As a convention, lets have the name of the getter functions started with the word get, and the setter functions started with word set, both followed by an underscore, and then followed by the name of data member. For example the getter for the data member hour should be called get_hour, and he setter for the data member hour should be called set_hour. Remember that getter functions must be declared as a const member function to make them read-only funcitons.

All setter functions must check the argument of the function not to exceed the minimum and maximum limits of the each data member. If the value of the argument is below or above the limit the functions are supposed to do nothing.

What To Do

If you haven’t already read the above sections “Read This First” and “Read This Second”, read them first. The recommended concept of helper function can help you to reduce the size of repeated code in your program. Then, download file lab7ExE.cpp from D2L. This file contains the code to be used for testing your class Clock.

Now, take the following steps to write the definition and implementation of your class Clock as instructed in the above “Read This Second” section.

  1. Create a header file called lab7Clock.h and write the definition of your class Clock in this file. Make sure to use the appropriate preprocessor directives (#ifndef, #define, and #endif), to prevent the compiler from duplication of the content of this header file during the compilation process.
  2. Create another file called lab7Clock.cpp and write the implementation of the member functions of class Clock in this file (remember to include “lab7Clock.h” ).
  3. Compile files lab7ExE.cpp (that contain the given main functions) and lab7Clock.cpp to create your executable file.
  4. If your program shows any compilation or runtime errors fix them until your program produces the expected output as mentioned in the given main function.
  5. Now you are done!

What To Submit

Submit your source code, lab7Clock.h, and lab7Clock.cpp, and the program’s output as part of your post-lab report on the D2L, Dropbox.