1. Analyze and write a comparison of C%u2019s malloc and free functions to C++%u
ID: 3536296 • Letter: 1
Question
1. Analyze and write a comparison of C%u2019s malloc and free functions to C++%u2019s new and
delete operators. What is the same and what is different? Is one safer than the other?
2.) Let the function fun be defined as:
int fun(int *k) {
*k += 10;
return 5 * (*k) - 2;
}
Suppose fun was used in a program as follows:
void main() {
int i = 8, j = 12, sum1, sum2;
sum1 = (i / 2) + fun(&i);
sum2 = fun(&j)) + ( j / 2);
}
What are the values of sum1 and sum2
a) If the operands in the expressions are valuated left to right?
b) if the operands in the expressions are evaluated right to left?
Explanation / Answer
malloc and free function
The function malloc is used to allocate a certain amount of memory during the execution of a program. The malloc function will request a block of memory from the heap. If the request is granted, the operating system will reserve the requested amount of memory.
When the amount of memory is not needed anymore, you must return it to the operating system by calling the function free.
new and delete operator
C++ supports dynamic allocation and deallocation of objects using the new and delete operators. These operators allocate memory for objects from a pool called the free store. The new operator calls the special function operator new, and the delete operator calls the special function operator delete.
In order to request dynamic memory we use the operator new. new is followed by a data type specifier and -if a sequence of more than one element is required- the number of these within brackets []. It returns a pointer to the beginning of the new block of memory allocated. Its form is:
pointer = new type
pointer = new type [number_of_elements]
example
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.