It is currently Fri May 26, 2017 1:56 pm




 Page 1 of 1 [ 3 posts ] 
Author Message
 Post subject: Can't delete dynamic alocated memory
PostPosted: Mon Feb 23, 2009 7:01 am 

Joined: Fri Jan 04, 2008 2:11 pm
Posts: 72
i wrote a code for a simple programming challenge but the problem is i can't delete the arrays i dynamically created...

without deleting the exe runs fine but if i try to delete the program crashes.

below is the code file, can somebody help me plz ??

these 2 lines are where the problem lies

   delete [] a1;
   //a1=NULL;
   delete [] a2;
   //a2=NULL;



http://rapidshare.com/files/201532432/USACO.zip.html


Offline
 Profile  
 
 Post subject: a.schedule=new int[iv3.size()]; // at wrong place
PostPosted: Mon Feb 23, 2009 6:19 pm 

Joined: Wed Aug 06, 2008 7:53 pm
Posts: 182
Location: Russia
Hi ir2pi.

It seems the problem in the following place:

struct IntArray Browsing::getSchedule(int browsingTime[], int noOfPersons, int timeSlot)
{
    int tot=0,*a1,*a2;

    a.schedule=new int[iv3.size()]; // <-- at the moment iv1.size() == 0 $$$$$$$$$$$$$$$$$$$$$$$$$$$



Move the memory allocation at the place when your iv1 vector is filled with items, i.e.
...
    a.schedule=new int[iv3.size()]; // <-- new place $$$$$$$$$$$$$$$$$$$$$$$$$$$
//  a.nSize = iv3.size();

    for(int i=0;i<(int)iv3.size();i++)
    {
        a.schedule[i]=iv3[i];
    }

    iv3.clear();

    delete [] a1;
    //a1=NULL;
    delete [] a2;
    //a2=NULL;

    return a;
}

Otherwise the statement a.schedule[i]=iv3[i] corrupts the heap memory.

After this update you should return the memory back to the system at the proper places.

...

void Browsing::del()
{
    delete [] a.schedule; // uncomment this
}

...
    //Testcase 1:
    {
        int browsingtime[] = {10,7,3,4,11};
        int size = 5;
        int time_slot = 5;
        struct IntArray res = bro.getSchedule(browsingtime, size, time_slot);
//      bro.del(); // <- not now $$$$$$$$$$$$$$$$$$$$$$$$$$$
        if(res.schedule != NULL)
        for(int i=0;i<res.nSize;i++)
            printf ("%d, ",res.schedule[i]);
        printf("\n");
        bro.del(); // <--- $$$$$$$$$$$$$$$$$$$$$$$$$$$
    }
...



;)



_________________
«Computer scientists deal with algorithms that you may call practical in theory but unpractical in practice.» © Timothy Gowers
Offline
 Profile  
 
 Post subject:
PostPosted: Mon Feb 23, 2009 11:56 pm 

Joined: Fri Jan 04, 2008 2:11 pm
Posts: 72
thanks for helping ...
i thought the problem was cuz i was trying to access deleted memory...
didn't realize the array was initialized to 0 size :oops:


Offline
 Profile  
 
Display posts from previous:  Sort by  
 Page 1 of 1 [ 3 posts ] 


Who is online

Users browsing this forum: No registered users and 1 guest


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Jump to:  

cron