analyze each program and figure out what is wrong with the memory management in the code and how to fix the code. #include <unistd.h>#include <stdio.h>#include <stdlib.h>#include <assert.h> // Hint: If you run this program repeatedly, with ever-larger numbers as input,// eventually something (slightly) unexpected should happen.intmain(int argc, char *argv[]){if (argc != 2) { fprintf(stderr, "usage: broken2 <value>\n"); exit(1); } int size = atoi(argv[1]);int *p;p = malloc(size*sizeof(int));for (int i = 0 ; i < size; i++) {p[i] = i;}int *q;q = malloc(sizeof(p));for (int i = 0 ; i < size; i++) {q[i] = p[i];} free(p);free(q);return 0;}

C++ Programming: From Problem Analysis to Program Design
8th Edition
ISBN:9781337102087
Author:D. S. Malik
Publisher:D. S. Malik
Chapter1: An Overview Of Computers And Programming Languages
Section: Chapter Questions
Problem 6SA
icon
Related questions
Topic Video
Question

analyze each program and figure out what is wrong with the memory management in the code and how to fix the code.

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

// Hint: If you run this program repeatedly, with ever-larger numbers as input,
// eventually something (slightly) unexpected should happen.
int
main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "usage: broken2 <value>\n");
exit(1);
}
int size = atoi(argv[1]);
int *p;
p = malloc(size*sizeof(int));
for (int i = 0 ; i < size; i++) {
p[i] = i;
}
int *q;
q = malloc(sizeof(p));
for (int i = 0 ; i < size; i++) {
q[i] = p[i];
}

free(p);
free(q);
return 0;
}

 

Expert Solution
trending now

Trending now

This is a popular solution!

steps

Step by step

Solved in 2 steps with 1 images

Blurred answer
Knowledge Booster
Instruction Format
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
  • SEE MORE QUESTIONS
Recommended textbooks for you
C++ Programming: From Problem Analysis to Program…
C++ Programming: From Problem Analysis to Program…
Computer Science
ISBN:
9781337102087
Author:
D. S. Malik
Publisher:
Cengage Learning