why does it crash? (C++ Linked lists)
http://rafb.net/paste/results/3hrmUS48.html
I was trying to write a simple linked list program.
it was working pretty good and i could see the results but in the end
its showing some DEBUG error..
i cant figure out whats the problum..
If by a "DEBUG" error, you mean an assertion failure in dbgheap.c, that's a memory corruption:
You forgot to allocate one extra byte for the '\0' character that marks the end of a string.
Since you are using C++, you should use the C++ std::string class rather than C-style strings. It would spare you that kind of error. The std::list class would likewise cover your linked-list needs.
There may be more errors in your code.
Quote:int cNameLength=strlen(cName),pNumberLength=strlen(pNumber);
PhoneNumber=new char [pNumberLength];
ClientName=new char [cNameLength];
You forgot to allocate one extra byte for the '\0' character that marks the end of a string.
Since you are using C++, you should use the C++ std::string class rather than C-style strings. It would spare you that kind of error. The std::list class would likewise cover your linked-list needs.
There may be more errors in your code.
that was probably it..
thanks, its working good now.
but can u show me how can i use the std::string?
thanks, its working good now.
but can u show me how can i use the std::string?
Quote:Original post by clearly
that was probably it..
thanks, its working good now.
but can u show me how can i use the std::string?
Click Me.
I'm too nice to people...
#include <iostream>#include <string>#include <list>#include <limits>class Data { std::string phoneNumber; std::string clientName; public: Data(const std::string& phoneNumber, const std::string& clientName) : phoneNumber(phoneNumber), clientName(clientName) {} friend ostream& operator<<(ostream& os, const Data& d) { return os << "Client name: " << clientName << "\n" << "Phone number: " << phoneNumber; }};template <typename T>bool readItem(T& result, istream& source) { bool success = (source >> result); source.clear(); source.ignore(std::numeric_limits<streamsize>::max(), '\n'); return success;}std::string readline(istream& source) { std::string result; std::getline(source, result); return result;}int main(int argc, char* argv[]) { typedef std::list<Data> datalist; datalist l; std::cout << "C++ standard library and typical C++ design idioms for fun and profit" << std::endl; while (true) { std::cout << "1. New client\n2. Quit" << std::endl; int c; if (readItem(c, std::cin) && c == 1) { std::cout << "\nInput phone number: " << std::flush; string phonenumber = readline(std::cin); std::cout << "Input client name: " << std::flush; string clientname = readline(std::cin); l.push_back(Data(phonenumber, clientname)); std::cout << "\nInsert succesfull..\n" << std::endl; } else { break; } } for (datalist::iterator it = l.begin(); it != l.end(); ++it) { std::cout << *it << std::endl; }}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement