Deallocation of memory..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
linkedlist *checkname(string s)
{
      linkedlist *temp=head; // linkedlist is a structure
      const char *c=s.c_str();
      char *dst=new char([strlen(c)+1];
      dst=temp->name;
      while(strcmp(c,dst)!=0)
      {
            if(temp->next==NULL)
            {
                  return NULL;
                  break;
            }
            else 
            {
             temp=temp->next;
             dst=temp->name;
             }
      }
      return temp;
}


In the above code,i guess i have to delete all that i have created using new.
But i am unable to figure out where do i delete them !

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
linkedlist *checkname(string s)
{
      linkedlist *temp=head; // linkedlist is a structure
      const char *c=s.c_str();
      char *dst=new char([strlen(c)+1];
      dst=temp->name;
      while(strcmp(c,dst)!=0)
      {
            if(temp->next==NULL)
            {
                  return NULL;
                  break;
            }
            else 
            {
             temp=temp->next;
             dst=temp->name;
             }
      }
      delete[] dst;
      return temp;
}


If i do the above, the program is giving an incorrect output !
please help
I don't think you need to allocate new memory for dst:

 
char *dst=new char([strlen(c)+1]; // not needed because you are not using that memory. 

change it to simply:
 
char *dst;


Then no need of deleting.
Thanks a lot !!

Can you please help me understand when do i have to allocate new memory and when do i dont have to !!

Thanks :)
For instance in this example you were first allocating new memory to pointer dst. Then you were assigning dst to point to temp->next. So your original memory already gets leaked at this stage because after this statement, the address of that new memory gets lost.

You can refresh your dynamic memory and pointer basics by going through the tutorial on this site.
Sure thing !! Thanks :)
Topic archived. No new replies allowed.