CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 15

Thread: My simple vector crashes

  1. #1
    Join Date
    Jun 2015
    Posts
    173

    My simple vector crashes

    Hi all,

    Here is the first version of my vector. It crashes and presumably the reason is the initializer list constructor, but I've used the version written in the Programming Principles and Practice Using C++ of the creator of cpp! Why the program crashes, please?

    Code:
    #include <iostream>
    #include <stdexcept>
    
    using namespace std;
    
    template <typename T>
    class myVec {
    
    public:
        myVec() { cout << "Default constructor is called.\n"; } // Default constructor
        myVec(const int&); // Ordinary onstructor
        myVec(initializer_list<T>); // Initializer list constructor
        
        ~myVec() { cout << "Destructor is called.\n"; delete[] elem; elem = nullptr; }  // Destructor - Release recources 
    
        const int size() const { return sz; }
    
    private:
        T* elem = nullptr;
        size_t sz = 0;
    };
    
    //******************************************************
    template <typename T>                           // Ordinary onstructor
    myVec<T>::myVec(const int& size) {
        cout << "Ordinary constructor is called.\n";
        if (size < 0) throw length_error{ "Negative Size" };
        elem = new T[size];
        sz = size;
    }
    
    //************************************************************
    
    template<typename T> 
    myVec<T>::myVec(initializer_list<T> lst) : sz { lst.size()}, elem {new T[sz]}
    {
        copy(lst.begin(), lst.end(), elem);
        cout << "Initializer list constructor is called.\n"; 
    }
    
    //***********************************************
    int main() try
    {
        myVec<int> vi1;
        myVec<int> vi2(10);
        myVec<int> vi3{ 2, 3, 4, 5 };
        
        cin.get();
        return 0;
    }
    
    catch (invalid_argument& e)
    {
        cerr << e.what() << "\n";
        abort();
    }
    catch (bad_alloc& e)
    {
        cerr << e.what() << "\n";
        abort();
    }
    catch (...)
    {
        cerr << "Something went wrong\n";
        abort();
    }

  2. #2
    VictorN's Avatar
    VictorN is online now Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    19,937

    Re: My simple vector crashes

    Quote Originally Posted by tomy12 View Post
    Hi all,

    Here is the first version of my vector. It crashes and presumably the reason is the initializer list constructor, ...
    Why presumably ?
    didn't you debug your code to see the exact place of the "crash"?
    Victor Nijegorodov

  3. #3
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,429

    Re: My simple vector crashes

    What os/compiler are you using? This compiles and runs OK with VS2019. I've only added an include for initialiser list.

    Code:
    #include <iostream>
    #include <stdexcept>
    #include <initializer_list>
    
    using namespace std;
    
    template <typename T>
    class myVec {
    
    public:
    	myVec() { cout << "Default constructor is called.\n"; } // Default constructor
    	myVec(const int&); // Ordinary constructor
    	myVec(initializer_list<T>); // Initializer list constructor
    
    	~myVec() { cout << "Destructor is called.\n"; delete[] elem; elem = nullptr; }  // Destructor - Release recources
    
    	const int size() const { return sz; }
    
    private:
    	T* elem = nullptr;
    	size_t sz = 0;
    };
    
    //******************************************************
    template <typename T>                           // Ordinary constructor
    myVec<T>::myVec(const int& size) {
    	cout << "Ordinary constructor is called.\n";
    	if (size < 0) throw length_error {"Negative Size"};
    	elem = new T[size];
    	sz = size;
    }
    
    //************************************************************
    
    template<typename T>
    myVec<T>::myVec(initializer_list<T> lst) : sz {lst.size()}, elem {new T[sz]}
    {
    	copy(lst.begin(), lst.end(), elem);
    	cout << "Initializer list constructor is called.\n";
    }
    
    //***********************************************
    int main() try
    {
    	myVec<int> vi1;
    	myVec<int> vi2(10);
    	myVec<int> vi3 {2, 3, 4, 5};
    
    	//cin.get();
    	return 0;
    }
    
    catch (invalid_argument& e)
    {
    	cerr << e.what() << "\n";
    	abort();
    }
    catch (bad_alloc& e)
    {
    	cerr << e.what() << "\n";
    	abort();
    }
    catch (...)
    {
    	cerr << "Something went wrong\n";
    	abort();
    }
    Code:
    Default constructor is called.
    Ordinary constructor is called.
    Initializer list constructor is called.
    Destructor is called.
    Destructor is called.
    Destructor is called.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++20 Compiler: Microsoft VS2019 (16.8.6)

  4. #4
    Join Date
    Jun 2015
    Posts
    173

    Re: My simple vector crashes

    I run my programs in Debug mode using VS 2019 with C++ 17 enabled.
    I added #include <initializer_list> but still get the run-time error message which is saying: HEAP CORRUPTION DETECTED, but I don't know how to find the error point in the code. What is the problem with my code, please?
    Last edited by tomy12; January 16th, 2021 at 12:07 PM.

  5. #5
    VictorN's Avatar
    VictorN is online now Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    19,937

    Re: My simple vector crashes

    Quote Originally Posted by tomy12 View Post
    I run my programs in Debug mode using VS 2019 with C++ 17 enabled.
    Run the "programs in Debug mode" is not the same as debug the program!
    Have a look at
    https://docs.microsoft.com/en-us/vis...s?view=vs-2019
    Victor Nijegorodov

  6. #6
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,429

    Re: My simple vector crashes

    OK. There is an ordering error in the initializer list constructor. The order of initialisation must be the same as the order the variables are defined. So you need as you're using sz before it's initialised.

    Code:
    template<typename T>
    myVec<T>::myVec(initializer_list<T> lst) : sz {lst.size()}, elem {new T[lst.size()]}
    {
    	copy(lst.begin(), lst.end(), elem);
    	cout << "Initializer list constructor is called.\n";
    }
    which compiles and runs OK with VS2019 in debug mode.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++20 Compiler: Microsoft VS2019 (16.8.6)

  7. #7
    Join Date
    Jun 2015
    Posts
    173

    Re: My simple vector crashes

    @VictoeN
    I recalled that method and using F10 and F11 tried to go through the code step by step to find the line containing the error but yet nothing except for the message above. I run my program in debug mode by F5 always.

    @2kaud
    Thank you. It solved the issue, surprisingly! Will you explain that matter a little more please? That order is rather odd.
    If I'm not mistaken, when I declare the data members in the class this way:

    Code:
    ...
    private:
    	size_t sz = 0;
    	T* elem = nullptr;
    };
    in the initializer constructor first sz must be initialized since it's declared before elem, and then elem can be initialized, this way:

    Code:
    template<typename T>   // Initializer list constructor
    myVec<T>::myVec(initializer_list<T> lst) : sz{ lst.size() }, elem{ new T[sz] }
    {
    	copy(lst.begin(), lst.end(), elem);
    	cout << "Initializer list constructor is called.\n";
    }
    Now it must work properly.

  8. #8
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,429

    Re: My simple vector crashes

    I would code it as this which also includes an overload so that the contents of myVec can be displayed:

    Code:
    #include <iostream>
    #include <initializer_list>
    #include <stdexcept>
    #include <algorithm>
    
    template <typename T>
    class myVec {
    
    public:
    	myVec() { std::cout << "Default constructor is called.\n"; } // Default constructor
    	myVec(size_t); // Ordinary constructor
    	myVec(const std::initializer_list<T>&); // Initializer list constructor
    
    	~myVec() { std::cout << "Destructor is called.\n"; delete[] elem; }  // Destructor - Release resources
    
    	auto size() const { return sz; }
    
    	template <typename U>
    	friend std::ostream& operator<<(std::ostream&, const myVec<U>&);
    
    private:
    	size_t sz {};
    	T* elem {};
    };
    
    template <typename U>
    std::ostream& operator<<(std::ostream& os, const myVec<U>& vec)
    {
    	for (size_t i = 0; i < vec.sz; ++i)
    		os << vec.elem[i] << "  ";
    
    	return os;
    }
    
    //******************************************************
    template <typename T>                           // Ordinary constructor
    myVec<T>::myVec(size_t size) : sz(size), elem(new T[size] {}) {
    	std::cout << "Ordinary constructor is called.\n";
    }
    
    //************************************************************
    
    template<typename T>
    myVec<T>::myVec(const std::initializer_list<T>& lst) : sz (lst.size()), elem (new T[lst.size()])
    {
    	std::copy(lst.begin(), lst.end(), elem);
    	std::cout << "Initializer list constructor is called.\n";
    }
    
    
    //***********************************************
    int main() try
    {
    	myVec<int> vi1;
    	myVec<int> vi2(10);
    	myVec<int> vi3 {2, 3, 4, 5};
    
    	std::cout << vi3 << '\n';
    
    	//cin.get();
    	return 0;
    }
    
    catch (std::invalid_argument& e)
    {
    	std::cerr << e.what() << "\n";
    	abort();
    }
    catch (std::bad_alloc& e)
    {
    	std::cerr << e.what() << "\n";
    	abort();
    }
    catch (...)
    {
    	std::cerr << "Something went wrong\n";
    	abort();
    }
    Code:
    Default constructor is called.
    Ordinary constructor is called.
    Initializer list constructor is called.
    2  3  4  5
    Destructor is called.
    Destructor is called.
    Destructor is called.
    Last edited by 2kaud; January 17th, 2021 at 04:57 AM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++20 Compiler: Microsoft VS2019 (16.8.6)

  9. #9
    Join Date
    Jun 2015
    Posts
    173

    Re: My simple vector crashes

    2 questions:

    1) Why did you change:
    Code:
     myVec(const int&); // Ordinary constructor
    	myVec(initializer_list<T>); // Initializer list constructor
    to

    Code:
     myVec(size_t); // Ordinary constructor
    	myVec(const initializer_list<T>&); // Initializer list constructor
    please? I mean both lines. What is the difference?

    and 2) Why can't we use that overloaded operator the following way? (I dislike friend!)

    Code:
    ostream& operator<<(ostream& os, const myVec<T>& vec) {
    		for (size_t i; i < vec.sz; i++)
    			os << vec.elem[i] << " ";
    		return os;
    	}

  10. #10
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,429

    Re: My simple vector crashes

    1) Pass by const ref - so not passed by value, so no copy of the passed argument undertaken. In general unless a copy is required, only POD types (int, char etc) are passed by value - others are passed by const ref instead of by value so no copy is undertaken. For performance reasons. Passed by vakue with a copy can be 'expensive' in performance terms.

    2) vec.sz and vec.elem are private so can only be referenced within the class. operator<<() is not part of the class and so cannot access these without operator() being a friend function which allows access to the private members. operator<<() can't be a member function as then it would have to be called as vec.operator<<() - but it isn't. It's called as operator<<() - so has to be in global space.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++20 Compiler: Microsoft VS2019 (16.8.6)

  11. #11
    Join Date
    Jun 2015
    Posts
    173

    Re: My simple vector crashes

    Thank you very much for your help.

  12. #12
    Join Date
    Jun 2015
    Posts
    173

    Re: My simple vector crashes

    @2kaud

    You're using Visual Studio 2019 compiler just like me. I want to find the source code of STL libraries inside it so that I can explore them at times I need but whatever I search I'm not able to find them on the Visual Studio directory. Will you tell me at what address you find them, please.

  13. #13
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,429

    Re: My simple vector crashes

    To look at the STL source code, just put your mouse cursor over the #inciude <...> statement in your code, right click and choose Go To Document... The file will then open within VS. Note the code isn't that easy to understand!
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++20 Compiler: Microsoft VS2019 (16.8.6)

  14. #14
    Join Date
    Jun 2015
    Posts
    173

    Re: My simple vector crashes

    Ah, **** it! Three thousand lines of code for a vector!?

  15. #15
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,429

    Re: My simple vector crashes

    Yep - although the std:: version has some additional features over yours. But that is how professional libraries are written - with heavy use of templated code, type_traits etc for support for non-ASCII etc etc etc
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++20 Compiler: Microsoft VS2019 (16.8.6)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)