Chapter 20 "Find highest element" example code (with templated high() function) - Help needed

31 views
Skip to first unread message

Osman Zakir

unread,
Nov 11, 2017, 11:07:46 AM11/11/17
to PPP-public
File attached to message.

With this code, the input loop for the vector won't run.  And there's also a heap corruption error occurring in get_from_jack() in there somewhere.  When I allocate more than 13 or so doubles for data_arr sometimes.  And even though it'll definitely leak memory without the delete[] on line 146, having it there triggers a breakpoint and it shows me this code:

void __CRTDECL operator delete(void* const block) noexcept
{
   
#ifdef _DEBUG
    _free_dbg
(block, _UNKNOWN_BLOCK);
   
#else
    free
(block);
   
#endif
}


the red mark indicating a breakpoint is on the _free_dbg(block, _UNKNOWN_BLOCK); line.  

Would someone please help me out here?  Thanks in advance.
 
main.cpp

Christiano

unread,
Nov 16, 2017, 12:36:30 PM11/16/17
to PPP-public
The book's code is:

void fct()
{
    int jack_count = 0;
    double *jack_data = get_from_jack(&jack_count);
    std::vector<double> *jill_data = get_from_jill();

    double *jack_high = high(jack_data, jack_data + jack_count);
    std::vector<double> &v = *jill_data;
    double *jill_high = high(&v[0], &v[0] + v.size());

    std::cout << "Jill's high " << *jill_high << "; Jack's high " << *jack_high << '\n';

    delete[] jack_data;
    delete jill_data;

}

The code
   double *jill_high = high(&v[0], &v[0] + v.size());
could be:
   double *jill_high = high(v.begin(), v.end());

The objective here is just to show the universality of algorithm high, you don't need to implement the functions. Probably your implementation of get_from_jack and get_from_jill is wrong. But you don't need to write it, you just need to understand that

get_from_jack returns a address for a array of doubles with size jack_count and it was allocated using new,
and
get_from_jill returns a address of vector<double> which was allocated using new as well.

Both work with function high, that is the point you need to get.

Osman Zakir

unread,
Dec 10, 2017, 11:31:11 AM12/10/17
to PPP-public
Well, yes, I do get that.  But there's also a "Try this" exercise that asks to debug the program and fix the two potential errors left in the program.  There's another "Try this" for the second version also asks to debug the second version of the program.  And there's an exercise among the ones at the end of the chapter as well that asks to get the Jack and Jill example to work and fix the errors using STL techniques.  I wanted to try those exercises.   

I've attached my latest attempts at the program to this message.  It seems to work now, but I wanted to know if the errors have been fixed.  
main.cpp
velocities1.txt
velocities2.txt
Reply all
Reply to author
Forward
0 new messages