HRusev

06. Memory Allocator

Jul 20th, 2023
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | Source Code | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <sstream>
  5.  
  6. #include "Defines.h"
  7.  
  8. ErrorCode executeCommand(const std::string& command, std::vector<int*>& memory)
  9. {
  10.     ErrorCode code = EXECUTE_SUCCESS;
  11.     static size_t buzyMemory = 0;
  12.     std::istringstream istr(command);
  13.     std::string com;
  14.     int index;
  15.     static bool isAllocate = false;
  16.  
  17.     istr >> com;
  18.     if (com != "Idle")
  19.     {
  20.         istr >> index;
  21.         if (index >= memory.size())
  22.             code = INDEX_OUT_OF_BOUND;
  23.         else if (com == "Allocate")
  24.         {
  25.             if (!isAllocate)
  26.             {
  27.                 buzyMemory += index;
  28.                 isAllocate = true;
  29.             }
  30.             else
  31.                 code = MEMORY_LEAK;
  32.            
  33.         }
  34.         else if (com == "Deallocate")
  35.         {
  36.             if (isAllocate && index == buzyMemory)
  37.             {
  38.                 buzyMemory = 0;
  39.                 isAllocate = false;
  40.             }
  41.             else
  42.                 code = DOUBLE_FREE;
  43.         }
  44.  
  45.     }
  46.     else
  47.         code = EXECUTE_IDLE;
  48.     return code;
  49. }
  50.  
  51. void printResult(const ErrorCode errorCode, const std::string& command)
  52. {
  53.     std::cout << command << " - ";
  54.    
  55.     switch (errorCode)
  56.     {
  57.     case EXECUTE_SUCCESS:
  58.         std::cout << "success" << std::endl;
  59.         break;
  60.     case EXECUTE_IDLE:
  61.         std::cout << "this exam is a piece of cake! Where is the OOP already?!?" << std::endl;
  62.         break;
  63.     case MEMORY_LEAK:
  64.         std::cout << "memory leak prevented, will not make allocation" << std::endl;
  65.         break;
  66.     case DOUBLE_FREE:
  67.         std::cout << "system crash prevented, will skip this deallocation" << std::endl;
  68.         break;
  69.     case INDEX_OUT_OF_BOUND:
  70.         std::cout << "out of bound" << std::endl;
  71.         break;
  72.     default:
  73.         break;
  74.     }
  75.  
  76. }
  77.  
  78.  
Advertisement
Add Comment
Please, Sign In to add comment