memory management – A Tic Tac Toe game in C++

It is considered a bad practice. This is because namespaces were introduced as a way to avoid name collisions, i.e Multiple objects with the same name. The std namespace is HUGE and has hundreds of common identifiers that can interfere with yours.

By doing using namespace std you now have no idea what function is a part of the std library, and what isn’t.

I think you have misunderstood the use of the new operator in C++. What is the use of dynamic memory allocation here? I fail to see a good reason to not simply create your variables on the stack. The problem here is you cannot forget to delete. If you do, you expose your program to memory leaks – Horrible.

You can use new when:

  • You don’t want an object to be destroyed until you call delete
  • When your object is very large

In short, there is no need to use the new operator here. It just introduces complications.

When to use the ‘new’ operator


/**********************************************************************************************************
Return 1 if some one wins
Return 0 if draw
Return -1 if the game is not over
***********************************************************************************************************/

the numbers 1, 0, -1 are known as magic numbers, your comment helps but one would have to keep referring back to know their meaning. Using an enum here will clear a lot

enum Result { Win, Draw, OnGoing };

return Result::Win;

That way you can declare your function as

Result checkWin();

And instead of

return (number which means nothing)

You do

return Result::Win;

int checkWin()
{
    if (squares(0) == squares(1) && squares(1) == squares(2))
    {
        return 1;
    }
    else if (squares(0) == squares(3) && squares(3) == squares(6))
    {
        return 1;
    }
    else if (squares(0) == squares(4) && squares(4) == squares(8))
    {
        return 1;
    }
    else if (squares(3) == squares(4) && squares(4) == squares(5))
    {
        return 1;
    }
    else if (squares(1) == squares(4) && squares(4) == squares(7))
    {
        return 1;
    }
    else if (squares(6) == squares(4) && squares(4) == squares(2))
    {
        return 1;
    }
    else if (squares(6) == squares(7) && squares(7) == squares(8))
    {
        return 1;
    }
    else if (squares(2) == squares(5) && squares(5) == squares(8))
    {
        return 1;
    }
    
}

A more readble way to do this would be to store the patterns in an array, and everytime you want to check for a winner, you iterate through the array and use them.

constexpr int winPatterns(8)(3){
    {0, 1, 2}, // first row
    {3, 4, 5},  // second row

    //...
};

Now when you want to check for a winner

for (int i = 0;i < 8;i++){
    auto line = winPatterns(i);

    if ( line(0) == line(1) and line(1) == line(2) ) return line(0);
}

Instead of checking whether each and every cell is occupied, use an int which is initially set to 0. Keep incrementing it after every turn. That way you can get the result like so

bool checkDraw(){
    return (checkWin() != Result::Win and counter == 9 );
}

It is simple. If the counter reaches 9 and no one has won yet, it is a draw because all the cells are occupied without a winner.


cout << "nntTic Tac Toenn";

    cout << "Player 1 (X)  -  Player 2 (O)" << endl
         << endl;
    cout << endl;

    cout << "     |     |     " << endl;
    cout << "  " << squares(0) << "  |  " << squares(1) << "  |  " << squares(2) << endl;

    cout << "_____|_____|_____" << endl;
    cout << "     |     |     " << endl;

    cout << "  " << squares(3) << "  |  " << squares(4) << "  |  " << squares(5) << endl;

    cout << "_____|_____|_____" << endl;
    cout << "     |     |     " << endl;

    cout << "  " << squares(6) << "  |  " << squares(7) << "  |  " << squares(8) << endl;

    cout << "     |     |     " << endl
         << endl;

You can use string literals here.

const char* Heading = R"(
        Tic Tac Toe

Player 1 (X)  -  Player 2 (O)

)";

std::cout << Heading;

comparative review – Memory management in my code

I am a beginner programmer and have made a tic tac toe program in c++. I need some help with my memory management can anyone review and help me. This is my code

// This is a trial for tic tac toe in C++
#include <iostream>
using namespace std;

char *squares = new char(9){'1', '2', '3', '4', '5', '6', '7', '8', '9'};

void play();
void getBoard();
int checkWin();

int main()
{
    char *playAgain = new char;
    do
    {
        play();
        cout << "Do you want to play again(y/n): ";
        cin >> *playAgain;

    } while (tolower(*playAgain) == 'y');
    delete squares, playAgain;
    cin.get();
    return 0;
}

//Play the game
void play()
{
    int *i = new int;
    int player = 1;
    int *choice = new int;
    char *mark = new char;

    do
    {
        getBoard();
        player = (player%2) ? 1 : 2;
        cout << "Enter your choice: ";
        cin >> *choice;
        *mark = (player == 1) ? 'X' : 'O';

        if (squares(0) == '1' && *choice == 1)
        {
            squares(0) = *mark;
        }
        else if (squares(1) == '2' && *choice == 2)
        {
            squares(1) = *mark;
        }
        else if (squares(2) == '3' && *choice == 3)
        {
            squares(2) = *mark;
        }
        else if (squares(3) == '4' && *choice == 4)
        {
            squares(3) = *mark;
        }
        else if (squares(4) == '5' && *choice == 5)
        {
            squares(4) = *mark;
        }
        else if (squares(5) == '6' && *choice == 6)
        {
            squares(5) = *mark;
        }
        else if (squares(6) == '7' && *choice == 7)
        {
            squares(6) = *mark;
        }
        else if (squares(7) == '8' && *choice == 8)
        {
            squares(7) = *mark;
        }
        else if (squares(8) == '9' && *choice == 9)
        {
            squares(8) = *mark;
        }
        else
        {
            cout << "Invalid move ";

            player--;
            cin.ignore();
            cin.get();
        }

        *i = checkWin();
        player++;

    } while (*i == -1);
    getBoard();
    if (*i == 1)
    {
        cout << "aPlayer " << --player << " Wins" << endl;
        delete mark, choice, i;
    }
    else
    {
        cout << "aGame Draw" << endl;
        delete mark, choice, i;
    }
}

// Print the board
void getBoard()
{
    cout << "nntTic Tac Toenn";

    cout << "Player 1 (X)  -  Player 2 (O)" << endl
         << endl;
    cout << endl;

    cout << "     |     |     " << endl;
    cout << "  " << squares(0) << "  |  " << squares(1) << "  |  " << squares(2) << endl;

    cout << "_____|_____|_____" << endl;
    cout << "     |     |     " << endl;

    cout << "  " << squares(3) << "  |  " << squares(4) << "  |  " << squares(5) << endl;

    cout << "_____|_____|_____" << endl;
    cout << "     |     |     " << endl;

    cout << "  " << squares(6) << "  |  " << squares(7) << "  |  " << squares(8) << endl;

    cout << "     |     |     " << endl
         << endl;
}

/**********************************************************************************************************
Return 1 if some one wins
Return 0 if draw
Return -1 if the game is not over
***********************************************************************************************************/

int checkWin()
{
    //TODO: Fix the function
    if (squares(0) == squares(1) && squares(1) == squares(2))
    {
        return 1;
    }
    else if (squares(0) == squares(3) && squares(3) == squares(6))
    {
        return 1;
    }
    else if (squares(0) == squares(4) && squares(4) == squares(8))
    {
        return 1;
    }
    else if (squares(3) == squares(4) && squares(4) == squares(5))
    {
        return 1;
    }
    else if (squares(1) == squares(4) && squares(4) == squares(7))
    {
        return 1;
    }
    else if (squares(6) == squares(4) && squares(4) == squares(2))
    {
        return 1;
    }
    else if (squares(6) == squares(7) && squares(7) == squares(8))
    {
        return 1;
    }
    else if (squares(2) == squares(5) && squares(5) == squares(8))
    {
        return 1;
    }
    else if (squares(0) != '1' && squares(1) != '2' && squares(2) != '3' && squares(3) != '4' && squares(4) != '5' && squares(5) != '6' && squares(6) != '7' && squares(7) != '8' && squares(8) != '9')
    {
        return 0;
    }
    else
    {
        return -1;
    }
}
```

What tools can be used to stream a data table out of sql server to a csv without reading it fully into memory?

I have a clunky script using BCP to pull a table without memory usage. I know I can use powershell commands to pull tables and write csvs but those commands read the entire table into memory, and I have some huge tables. Are there any other command line tools that will let me stream a table out of sql server (on the local windows machine) and into a csv?

export – Memory usage for importing and exporting

I’ve been encountering troubles in the process of exporting and importing my generated data.
I’m trying to save a variable of size {50,000 5000} in mx format, but besides taking a lot of time,
it seems to eat all my Ram.

I’m currently working on a 15Gb Ram computer, and it doesn’t seems to have problem loading big
datasets in other coding apps.

I would like to know if there is something i might be doing wrong, or if i should consider expanding
my Ram size to 32Gb.

Sorry if the question is too vague, i don’t know a lot about computers, so i don’t know what other information to share.

Here an example of the code to export:

Export(ToString(pathvxy.mx), vxy);

Dimensions(vxy)
{50000, 5000}

and then to import:

vxy = Import(ToString(pathvxy.mx));

Exporting always succeds, but the import always fails due to a memory fail (?).

Any suggestions or hints to solve the problem are appeciated!

kernel – How to get information about segments of physical memory not described in System.map on linux

When I do in linux root shell ”’cat /boot/System.map-uname -r”’ it returns me segments of memory but there is a big gap arround phys_startup_64:
”’
00000000000228c0 D softnet_data
0000000000022a80 d rt_uncached_list
0000000000022ac0 d rt6_uncached_list
0000000000023000 d kvm_apic_eoi
0000000000023040 d steal_time
0000000000023080 d apf_reason
0000000000024000 D __per_cpu_end
0000000001000000 A phys_startup_64
ffffffff81000000 T _stext
ffffffff81000000 T _text
ffffffff81000000 T startup_64
ffffffff81000030 T secondary_startup_64
ffffffff810000e0 T verify_cpu
ffffffff810001e0 T start_cpu0
ffffffff810001f0 T __startup_64
ffffffff810003f0 T pvh_start_xen
”’
I know that after ”’__per_cpu_end”’ there are some PCI devices and understand even root user wouldn’t have full access from security reasons but what are there any switches or ways to recompile kernel to learn about this on live system, using live addresses and devices ?
What exacts kinds of memory ranges are reserved and for what particular reasons ?

nosql – What is the damage to the database if it uses high memory storage? Are there consequences for this use? Does it affect performance?

To add on to danblack’s point, it’s generally good for your server’s memory to be mostly consumed by the database system because accessing data from memory is faster than disk, but if you don’t have enough memory to support your database system’s workload then you can run into performance issues when it needs to pull from disk or compensate in other ways.

If you updated your question with the specific issue you’re trying to solve then we can provide more specific information, but if you’re just generally asking then you don’t have to worry too much about this until you run into performance issues. There’s a lot of other things that can equally or more likely affect performance before memory provision does.

memory – Why does my program slows down a lot on server?

My python program (single threaded) uses 59 seconds to process a file on my Mac Pro, and it’s info is below:

MacBook Pro (15-inch, 2019)
2.4 GHz 8-Core Intel Core i9
16 GB 2400 MHz DDR4
Radeon Pro 560X 4 GB
Intel UHD Graphics 630 1536 MB 

However, it takes 1.43 minute to process the same file on a server, which have multiple cores. The CentOs cpus is below:

# cat /proc/cpuinfo
processor   : 0
vendor_id   : GenuineIntel
cpu family  : 6
model       : 85
model name  : Intel(R) Xeon(R) Silver 4114 CPU @ 2.20GHz
stepping    : 4
microcode   : 0x1
cpu MHz     : 2200.002
cache size  : 14080 KB
physical id : 0
siblings    : 32
core id     : 0
cpu cores   : 16
apicid      : 0
initial apicid  : 0
fpu     : yes
fpu_exception   : yes
cpuid level : 13
wp      : yes
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm mpx avx512f avx512dq rdseed adx smap avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1
bogomips    : 4400.00
clflush size    : 64
cache_alignment : 64
address sizes   : 46 bits physical, 48 bits virtual
power management:

# free -mh 
              total        used        free      shared  buff/cache   available
Mem:           220G         26G         10G        1.2G        183G        191G

Each container probably has 2 cores with 8G memory each.

Does it make sense that the CentOs takes almost double time to complete the same task?

javascript – Choose random string from set without loading them all to memory

So I have some code that runs perfectly fine, but the issue is that I do not want to load all the possible choices to memory. Even though at this stage that wouldn’t really matter, at some point there will be a lot of choices and the array will become huge.

First File:

var opponentDictionary=(
    "catastrophe","feline","canine","hazard","zoologist","scientist","uranium","advertise","plumb","collar","golden","sapphire","spade","sidewalk","freeway","plumber",
    "umbrella","telling","lieutenant","attendant","secretary"
);

(Excerpt from) Second File:

opponentWord=opponentDictionary(Math.floor(Math.random()*opponentDictionary.length));

Preferably I wouldn’t want to create a file per word, and I don’t want something super complex that makes it so much of a hassle to deal with and outweighs the reason for changing it, not loading the memory with like hundreds of strings. I know this is just JavaScript so its not memory based, but is there a better way to do this?

computer architecture – Memory Invalidation and Misses

Assume this particular architecture of a machine. Say we have 4 processors and each processor has its private L1 cache and shared L2 cache. Now if we write to an address in one of the private cache’s of the L1 cache then we Invalidate the blocks in the other private cache which contains the same address. Say P0(processor 0) reads an address 100 and so the block containing it say B0 gets stored in the private cache of P0 and as well as in the shared L2 cache. Now say P2 writes to the location 100. So we need to invalidate the block B0 from the private cache of P0. Now if P0 wants to read from address 100 again it will suffer a miss in its private cache, but will it get HIT or MISS in the L2 cache?

I think it will get HIT. Can anyone confirm.

windows server 2012 – IIS increase in worker process memory when RAM is increased

I have a few IIS servers serving web traffic.

In the past these were running off 4GB of RAM and the available RAM was always around 500MB of available RAM, there are 6 app pools and thus 6 worker processes.

When I upped the RAM to 8GB it looks like the worker processes are consuming more memory despite no code change, is this expected due to how IIS works ? i.e. if I increase RAM will the same worker processes be more liberal with their memory usage? (or potentially not garbage collect as often?).

Can anyone explain this?