• C++ bad dynamic memory
    3 replies, posted
I have a problem with dynamic memory and I get these errors, I fixed them before but I can't remember how :S First-chance exception at 0x75af42eb in Test.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x0023fb68.. First-chance exception at 0x010b227b in Test.exe: 0xC0000005: Access violation writing location 0x00000000. Unhandled exception at 0x010b227b in Test.exe: 0xC0000005: Access violation writing location 0x00000000. [cpp] // map.hpp #ifndef MAP #define MAP #include <iostream> #include <new> class Map { private: int Width,Height; int * map; public: Map(int W,int H); void SetHeight(int x,int y,int height); void Showmap(); }; #endif // map.cpp #include "map.hpp" Map::Map(int W, int H) { map = new (std::nothrow) int[Width*Height]; Width = W; Height = H; for (int n=0; n<Height; n++) { for (int m=0; m<Width; m++) { map[n*Width+m] = 0; } } } void Map::SetHeight(int x,int y,int height) { } void Map::Showmap() { for (int n=0; n<Height; n++) { for (int m=0; m<Width; m++) { std::cout<< map[n*Width+m]; } std::cout << std::endl; } } // main.cpp #include <iostream> #include <stdlib.h> #include <time.h> #include "map.hpp" int random(int start,int stop) { return rand() % stop + start; } int main() { int Height,Width; srand(time(NULL)); std::cout << "Map Generator !" << std::endl << std::endl; std::cout << "Input the number height and lenght" << std::endl; std::cout << "Height : "; std::cin >> Height; std::cout << std::endl << "Width : "; std::cin >> Width; Map map (Width, Height); std::cout << "Press any key to continue..."; std::cin.ignore(); std::cin.get(); return 1; } [/cpp]
[code]map = new (std::nothrow) int[Width*Height]; [/code] You have not set width and height to anything yet.
Thanks, Fucking noob mistake
Why would you use nothrow if you aren't going to check for errors? That's the biggest mistake you've made, IMO.
Sorry, you need to Log In to post a reply to this thread.