Home > database >  In which one of the following two codes does memory leak occur? My professor says that its A, but I
In which one of the following two codes does memory leak occur? My professor says that its A, but I

Time:10-24

My question here is that according to my professor, while in Program A, get_Name() causes memory leak, it doesn't cause any in Program B. I do not get why this is the case!

From what I can gather, there should be memory leak happening at get_Name() becuase malloc() is used. What I don't get is why case A? Any answers will be appreciated.

PROGRAM A:

struct actor {
    char name[32];
    struct actor *next;
} *head = NULL;

char *get_name()
{  char *q;
   q = (char *) malloc(32);
   printf("Please enter a name: ");
   scanf("%s", q); return q;
};
int insertion()
{struct actor *c; char *n;
   c = malloc(sizeof(struct actor));
   if (c == 0) {
       printf("out of memory\n");  return -1;}
   n = get_name();
   strcpy(c->name, n);
   c->next = head;
   head = c;
   return 1
};

PROGRAM B:

struct actor {
    char *name;
    struct actor *next;
} *head = NULL;

char *get_name()
{  char *q;
   q = (char *) malloc(32);
   printf("Please enter a name: ");
   scanf("%s", q); return q;
};
int insertion()
{struct actor *c; char *n;
   c = malloc(sizeof(struct actor));
   if (c == 0) {
       printf("out of memory\n");  return -1;}
   c->name = get_name();
   c->next = head;
   head = c;
   return 1
};

CodePudding user response:

The insertion() method from sample A string-copies the result of get_name() into a new string whereas the insertion in sample B copies the obtained pointer into a list that starts at head. Somewhere lateron in the program, there must be a place where the complete list or its elements are deallocated by calling free(). This is not possible in sample A as the pointer to the string allocated with malloc() got lost after leaving insertion().

  • Related