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

#include <stdio.h> #include <stdlib.h> #include <string.h> #define BLOCKSIZE 409

ID: 3872965 • Letter: #

Question

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BLOCKSIZE 4096

char* make_copy(int i, char* string) {
int len;
char *s;

len = strlen(string);
s = (char*)malloc(len);
strncpy(s, string, len);
if( !(i%1000) )
printf("i=%d, %s ", i, s);
}

main() {
int i;
char *ptr, *string = "find the bugs!";

for(i=0; i<10000; i++) {
ptr = malloc(BLOCKSIZE);
strcpy(ptr, string);
make_copy(i, ptr);
  
}
}

FIX ALL THE ERROR IN THIS C CODE INCLUDING FREEING ALL THE ALLOCATED MEMORY

Explanation / Answer

Hi,

Whenever we use malloc, the memory is allocated from heap, hence its essential to free the space once we are done with them, like below,
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BLOCKSIZE 4096
char* make_copy(int i, char* string) {
int len;
char *s;
len = strlen(string);
s = (char*)malloc(len);
strncpy(s, string, len);
if( !(i%1000) )
printf("i=%d, %s ", i, s);
free(s);
}
main() {
int i;
char *ptr, *string = "find the bugs!";
for(i=0; i<10000; i++) {
ptr = malloc(BLOCKSIZE);
strcpy(ptr, string);
make_copy(i, ptr);
  
}
free(ptr);
}
Other than this, your code is technically correct, so unless you tell us the expected o/p this is correct functionally too.
Thumbs up if this was helpful, otherwise let me know in comments.