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

Consider the following fragment of code which is meant to add two together two x

ID: 3886802 • Letter: C

Question

Consider the following fragment of code which is meant to add two together two xy points, and answer the two questions below: struct point { int x: int y }: struct point* add_points(struct point*p1, struct point*p2) { struct point result: result.x = p1 rightarrow x + p2 rightarrow x: result.y = p1 rightarrow y + p2 rightarrow y: return&result;: } Most of the time function will appear to work fine, but then later there will be an issue with the result point's data changing unexpectly. a) What is the problem? b) How it can be fixed?

Explanation / Answer

a) the problem with the program is that we are creating pointers for the use but not deleting it and returning it back to the memory. Which results into memory leak. This causes program failures.

b) the program can be fixed by using pass by value only and not using pointers as per below: -

struct point {

int x;

int y;

};

struct point add_point(struct point p1,struct point p2) {

struct point result;

result.x = p1.x + p2.x;

result.y = p1.y + p2.y;

return result;

}

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