Thread: What is the problem with the code?

  1. #1
    Registered User
    Join Date
    May 2020
    Posts
    3

    What is the problem with the code?

    Does not run the code or or it runs incorrectly. And
    does not make .cs files only mode4_connectioncount.csv.
    Where is the mistake?

    Code:
    #include <stdio.h>
    #include <math.h>
    #include <stdlib.h>
    #include <time.h>
    #include <stdbool.h>
    
    enum strategy
    {
        DOVE, 
        HAWK  
    };
    
    struct player
    {
        enum strategy strat; 
        struct player** neighbors; 
        int neighborCount; 
    };
    
    
    double GetValue(struct player* plyr, double prize, double hawkWinningMultiplier)
    {
        int value = 0;
    
        
        for (int i = 0; i < plyr->neighborCount; i++)
        {
            if (plyr->strat == DOVE)
            {
                if (plyr->neighbors[i]->strat == HAWK)
                {
                }
                else
                {
                    value += prize;
                }
            }
            else
            {
                if (plyr->neighbors[i]->strat == HAWK)
                {
                }
                else
                {
                    value += hawkWinningMultiplier * prize;
                }
            }
        }
        return value;
    }
    
    bool AddConnection(struct player* plyr1, struct player* plyr2)
    {
        for (int i = 0; i < plyr1->neighborCount; i++)
        {
            if (plyr1->neighbors[i] == plyr2)
            {
                return false;
            }
        }
    
        struct player** tmp;
    
        
        tmp = (struct player*)malloc(sizeof(struct player) * (plyr1->neighborCount + 1));
    
        for (int i = 0; i < plyr1->neighborCount; i++)
        {
            tmp[i] = (plyr1->neighbors[i]);
        }
    
        tmp[plyr1->neighborCount] = plyr2;
        plyr1->neighborCount++;
    
        plyr1->neighbors = (struct player**)realloc(plyr1->neighbors, sizeof(struct player*) * plyr1->neighborCount);
    
        for (int i = 0; i < plyr1->neighborCount; i++)
        {
            plyr1->neighbors[i] = tmp[i];
        }
    
        free(tmp);
    
        
        tmp = (struct player*)malloc(sizeof(struct player) * (plyr2->neighborCount + 1));
    
        for (int i = 0; i < plyr2->neighborCount; i++)
        {
            tmp[i] = (plyr2->neighbors[i]);
        }
    
        tmp[plyr2->neighborCount] = plyr1;
        plyr2->neighborCount++;
    
        plyr2->neighbors = (struct player**)realloc(plyr2->neighbors, sizeof(struct player*) * plyr2->neighborCount);
    
        for (int i = 0; i < plyr2->neighborCount; i++)
        {
            plyr2->neighbors[i] = tmp[i];
        }
    
        free(tmp);
        return true;
    }
    
    
    struct player CreatePlayer(enum strategy str)
    {
        struct player plyr;
        plyr.neighborCount = 0;
        plyr.neighbors = malloc(0);
        plyr.strat = str;
        return plyr;
    }
    
    bool getBoolWithProbability(double probability)
    {
        double random_value;
    
        random_value = (double)rand() / RAND_MAX;
    
        return (random_value < probability);
    }
    
    
    void PlayPlayer(struct player* playingPlayer, double prize, double hawkWinningMultiplier)
    {
        int index = rand() % playingPlayer->neighborCount;
        struct player* other = playingPlayer->neighbors[index];
    
        if (GetValue(playingPlayer, prize, hawkWinningMultiplier) < GetValue(other, prize, hawkWinningMultiplier) && playingPlayer->strat != other->strat)
        {
            double delta_p = GetValue(other, prize, hawkWinningMultiplier) - GetValue(playingPlayer, prize, hawkWinningMultiplier);
            double p_max = fmax(playingPlayer->neighborCount, other->neighborCount);
            bool result = getBoolWithProbability(exp(-(delta_p / p_max)));
    
            if (result)
            {
                if (playingPlayer->strat == HAWK)
                {
                    playingPlayer->strat = DOVE;
                }
                else
                {
                    playingPlayer->strat = HAWK;
                }
            }
        }
    }
    
    
    double game(double prize, int gameCount, double hawkWinningMultiplier, int playerCount)
    {
            
            struct player* players = (struct player*)malloc(sizeof(struct player) * playerCount);
    
            for (int i = 0; i < playerCount; i++)
            {
                enum strategy strat = HAWK;
                if (getBoolWithProbability(0.5))
                {
                    strat = DOVE;
                }
    
                players[i] = CreatePlayer(strat);
            }
    
            
            AddConnection(&players[0], &players[1]);
            AddConnection(&players[2], &players[1]);
            AddConnection(&players[0], &players[2]);
    
            int connectionCount = 6;
    
            for (int i = 3; i < playerCount; i++)
            {
                int index = rand() % connectionCount;
    
                for (int j = 0; j < playerCount; j++)
                {
                    index -= players[j].neighborCount;
                    if (index <= 0)
                    {
                        AddConnection(&players[i], &players[j]);
                        connectionCount += 2;
                    }
                }
            }
    
            
            int doves = 0;
            int hawks = 0;
            int maxConnections = 0;
    
            for (int i = 0; i < playerCount; i++)
            {
                if (players[i].strat == HAWK)
                {
                    hawks += 1;
                }
                else
                {
                    doves += 1;
                }
                if (players[i].neighborCount > maxConnections)
                {
                    maxConnections = players[i].neighborCount;
                }
            }
    
            int* connections = (int*)malloc(sizeof(int) * maxConnections); //connection[x] is the count of players with x connections
    
            for (int i = 0; i < maxConnections; i++)
            {
                connections[i] = 0;
            }
            printf("START: Doves: %i, hawks: %i \n", doves, hawks);
    
            for (int i = 0; i < gameCount; i++)
            {
                int index = rand() % playerCount;
                PlayPlayer(&players[index], prize, hawkWinningMultiplier);
            }
            doves = 0;
            hawks = 0;
    
            for (int i = 0; i < playerCount; i++)
            {
                if (players[i].strat == HAWK)
                {
                    hawks += 1;
                }
                else
                {
                    doves += 1;
                }
                connections[players[i].neighborCount] += 1;
            }
            printf("END: Doves: %i, hawks: %i \n", doves, hawks);
    
            FILE* fp;
            fp = fopen("mode4_connectioncount.csv", "w"); 
    
            fprintf(fp, "connection count; number of players;\n");
    
            for (int i = 0; i < maxConnections; i++)
            {
                fprintf(fp, "%i; %i;\n", i, connections[i]);
            }
            fclose(fp);
    
            return ((double)doves) / (doves + hawks);
    
    }
    
    void testGameCount(double prize, int gameCount, double hawkMultiplier, int playerCount, int repetitionCount)
    {
        double* averages = (double*)malloc(gameCount * sizeof(double));
    
        for (int i = 0; i < gameCount; i++)
        {
            double result = 0;
    
            for (int j = 0; j < repetitionCount; j++)
            {
                result += game(prize, i + 1, hawkMultiplier, playerCount);
            }
    
            result = result / repetitionCount;
    
            result = result / repetitionCount;
            averages[i] = result;
        }
    
        FILE* fp;
        char* buf[30];
        snprintf(buf, 30, "mode%i_gameCountTest.csv");
        fp = fopen(buf, "w"); 
    
        fprintf(fp, "game count; percentage of doves;\n");
    
        for (int i = 0; i < gameCount; i++)
        {
            fprintf(fp, "%i; %f;\n", i + 1, averages[i]);
        }
        fclose(fp);
    }
    
    void testPrizeAmount(double prize, int gameCount, double hawkMultiplier, int playerCount, int repetitionCount)
    {
        double* averages = (double*)malloc(gameCount * sizeof(double));
    
        int x = 0;
        for (double i = 0; i < prize; i += 0.1, x++)
        {
            double result = 0;
    
            for (int j = 0; j < repetitionCount; j++)
            {
                result += game(i, gameCount, hawkMultiplier, playerCount);
            }
    
            result = result / repetitionCount;
    
            result = result / repetitionCount;
            averages[x] = result;
        }
    
        FILE* fp;
        char* buf[30];
        snprintf(buf, 30, "mode%i_PrizeAmountTest.csv");
        fp = fopen(buf, "w"); 
    
        fprintf(fp, "prize amount; percentage of doves;\n");
    
        x = 0;
        for (double i = 0; i < prize; i += 0.1, x++)
        {
            fprintf(fp, "%i; %f;\n", (double)i / 10, averages[x]);
        }
        fclose(fp);
    }
    
    
    void testPlayerCount(double prize, int gameCount, double hawkMultiplier, int playerCount, int repetitionCount)
    {
        double* averages = (double*)malloc((playerCount - 1) * sizeof(double));
    
        for (int i = 1; i < playerCount; i++)
        {
            double result = 0;
    
            for (int j = 0; j < repetitionCount; j++)
            {
                result += game(prize, gameCount, hawkMultiplier, i);
            }
    
            result = result / repetitionCount;
    
            result = result / repetitionCount;
            averages[i] = result;
        }
    
        FILE* fp;
        char* buf[30];
        snprintf(buf, 30, "mode%i_playerCountTest.csv");
        fp = fopen(buf, "w"); //Saving data to file
    
        fprintf(fp, "player count; percentage of doves;\n");
    
        for (int i = 0; i < playerCount; i++)
        {
            fprintf(fp, "%i; %f;\n", i + 1, averages[i]);
        }
        fclose(fp);
    }
    
    int main()
    {
        const int repetitionCount = 20;
    
        double prize = 1.0; 
        int gameCount = 50; 
        double hawkMultiplier = 1.5; 
        int playerCount = 50; 
    
        testGameCount(prize, gameCount, hawkMultiplier, playerCount, repetitionCount);
        testPrizeAmount(prize, gameCount, hawkMultiplier, playerCount, repetitionCount);
        testPlayerCount(prize, gameCount, hawkMultiplier, playerCount, repetitionCount);
        
    
        return 0;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,163
    Well before you get to run anything, fix all the warnings (which are errors).
    Code:
    $ gcc -std=c99 -Wall -Wextra bar.c -lm
    bar.c: In function ‘AddConnection’:
    bar.c:65:9: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
         tmp = (struct player*)malloc(sizeof(struct player) * (plyr1->neighborCount + 1));
             ^
    bar.c:85:9: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
         tmp = (struct player*)malloc(sizeof(struct player) * (plyr2->neighborCount + 1));
             ^
    bar.c: In function ‘testGameCount’:
    bar.c:277:14: warning: passing argument 1 of ‘snprintf’ from incompatible pointer type [-Wincompatible-pointer-types]
         snprintf(buf, 30, "mode%i_gameCountTest.csv");
                  ^
    In file included from bar.c:1:0:
    /usr/include/stdio.h:386:12: note: expected ‘char * restrict’ but argument is of type ‘char **’
     extern int snprintf (char *__restrict __s, size_t __maxlen,
                ^
    bar.c:277:23: warning: format ‘%i’ expects a matching ‘int’ argument [-Wformat=]
         snprintf(buf, 30, "mode%i_gameCountTest.csv");
                           ^
    bar.c:277:23: warning: format ‘%i’ expects a matching ‘int’ argument [-Wformat=]
    bar.c:278:16: warning: passing argument 1 of ‘fopen’ from incompatible pointer type [-Wincompatible-pointer-types]
         fp = fopen(buf, "w");
                    ^
    In file included from bar.c:1:0:
    /usr/include/stdio.h:272:14: note: expected ‘const char * restrict’ but argument is of type ‘char **’
     extern FILE *fopen (const char *__restrict __filename,
                  ^
    bar.c: In function ‘testPrizeAmount’:
    bar.c:311:14: warning: passing argument 1 of ‘snprintf’ from incompatible pointer type [-Wincompatible-pointer-types]
         snprintf(buf, 30, "mode%i_PrizeAmountTest.csv");
                  ^
    In file included from bar.c:1:0:
    /usr/include/stdio.h:386:12: note: expected ‘char * restrict’ but argument is of type ‘char **’
     extern int snprintf (char *__restrict __s, size_t __maxlen,
                ^
    bar.c:311:23: warning: format ‘%i’ expects a matching ‘int’ argument [-Wformat=]
         snprintf(buf, 30, "mode%i_PrizeAmountTest.csv");
                           ^
    bar.c:311:23: warning: format ‘%i’ expects a matching ‘int’ argument [-Wformat=]
    bar.c:312:16: warning: passing argument 1 of ‘fopen’ from incompatible pointer type [-Wincompatible-pointer-types]
         fp = fopen(buf, "w");
                    ^
    In file included from bar.c:1:0:
    /usr/include/stdio.h:272:14: note: expected ‘const char * restrict’ but argument is of type ‘char **’
     extern FILE *fopen (const char *__restrict __filename,
                  ^
    bar.c:319:21: warning: format ‘%i’ expects argument of type ‘int’, but argument 3 has type ‘double’ [-Wformat=]
             fprintf(fp, "%i; %f;\n", (double)i / 10, averages[x]);
                         ^
    bar.c: In function ‘testPlayerCount’:
    bar.c:346:14: warning: passing argument 1 of ‘snprintf’ from incompatible pointer type [-Wincompatible-pointer-types]
         snprintf(buf, 30, "mode%i_playerCountTest.csv");
                  ^
    In file included from bar.c:1:0:
    /usr/include/stdio.h:386:12: note: expected ‘char * restrict’ but argument is of type ‘char **’
     extern int snprintf (char *__restrict __s, size_t __maxlen,
                ^
    bar.c:346:23: warning: format ‘%i’ expects a matching ‘int’ argument [-Wformat=]
         snprintf(buf, 30, "mode%i_playerCountTest.csv");
                           ^
    bar.c:346:23: warning: format ‘%i’ expects a matching ‘int’ argument [-Wformat=]
    bar.c:347:16: warning: passing argument 1 of ‘fopen’ from incompatible pointer type [-Wincompatible-pointer-types]
         fp = fopen(buf, "w"); //Saving data to file
                    ^
    In file included from bar.c:1:0:
    /usr/include/stdio.h:272:14: note: expected ‘const char * restrict’ but argument is of type ‘char **’
     extern FILE *fopen (const char *__restrict __filename,
                  ^
    $
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    May 2020
    Posts
    3
    It's still not working

    Code:
    #include <stdio.h>
    #include <math.h>
    #include <stdlib.h>
    #include <time.h>
    #include <stdbool.h>
    
    enum strategy
    {
        DOVE,
        HAWK
    };
    
    struct player
    {
        enum strategy strat;
        struct player** neighbors;
        int neighborCount;
    };
    
    
    double GetValue(struct player* plyr, double prize, double hawkWinningMultiplier)
    {
        int value = 0;
    
    
        for (int i = 0; i < plyr->neighborCount; i++)
        {
            if (plyr->strat == DOVE)
            {
                if (plyr->neighbors[i]->strat == HAWK)
                {
                }
                else
                {
                    value += prize;
                }
            }
            else
            {
                if (plyr->neighbors[i]->strat == HAWK)
                {
                }
                else
                {
                    value += hawkWinningMultiplier * prize;
                }
            }
        }
        return value;
    }
    
    bool AddConnection(struct player* plyr1, struct player* plyr2)
    {
        for (int i = 0; i < plyr1->neighborCount; i++)
        {
            if (plyr1->neighbors[i] == plyr2)
            {
                return false;
            }
        }
    
        struct player** tmp;
    
    
        tmp = (struct player**)malloc(sizeof(struct player) * (plyr1->neighborCount + 1));
    
        for (int i = 0; i < plyr1->neighborCount; i++)
        {
            tmp[i] = (plyr1->neighbors[i]);
        }
    
        tmp[plyr1->neighborCount] = plyr2;
        plyr1->neighborCount++;
    
        plyr1->neighbors = (struct player**)realloc(plyr1->neighbors, sizeof(struct player*) * plyr1->neighborCount);
    
        for (int i = 0; i < plyr1->neighborCount; i++)
        {
            plyr1->neighbors[i] = tmp[i];
        }
    
        free(tmp);
    
    
        tmp = (struct player**)malloc(sizeof(struct player) * (plyr2->neighborCount + 1));
    
        for (int i = 0; i < plyr2->neighborCount; i++)
        {
            tmp[i] = (plyr2->neighbors[i]);
        }
    
        tmp[plyr2->neighborCount] = plyr1;
        plyr2->neighborCount++;
    
        plyr2->neighbors = (struct player**)realloc(plyr2->neighbors, sizeof(struct player*) * plyr2->neighborCount);
    
        for (int i = 0; i < plyr2->neighborCount; i++)
        {
            plyr2->neighbors[i] = tmp[i];
        }
    
        free(tmp);
        return true;
    }
    
    
    struct player CreatePlayer(enum strategy str)
    {
        struct player plyr;
        plyr.neighborCount = 0;
        plyr.neighbors = malloc(0);
        plyr.strat = str;
        return plyr;
    }
    
    bool getBoolWithProbability(double probability)
    {
        double random_value;
    
        random_value = (double)rand() / RAND_MAX;
    
        return (random_value < probability);
    }
    
    
    void PlayPlayer(struct player* playingPlayer, double prize, double hawkWinningMultiplier)
    {
        int index = rand() % playingPlayer->neighborCount;
        struct player* other = playingPlayer->neighbors[index];
    
        if (GetValue(playingPlayer, prize, hawkWinningMultiplier) < GetValue(other, prize, hawkWinningMultiplier) && playingPlayer->strat != other->strat)
        {
            double delta_p = GetValue(other, prize, hawkWinningMultiplier) - GetValue(playingPlayer, prize, hawkWinningMultiplier);
            double p_max = fmax(playingPlayer->neighborCount, other->neighborCount);
            bool result = getBoolWithProbability(exp(-(delta_p / p_max)));
    
            if (result)
            {
                if (playingPlayer->strat == HAWK)
                {
                    playingPlayer->strat = DOVE;
                }
                else
                {
                    playingPlayer->strat = HAWK;
                }
            }
        }
    }
    
    
    double game(double prize, int gameCount, double hawkWinningMultiplier, int playerCount)
    {
    
            struct player* players = (struct player*)malloc(sizeof(struct player) * playerCount);
    
            for (int i = 0; i < playerCount; i++)
            {
                enum strategy strat = HAWK;
                if (getBoolWithProbability(0.5))
                {
                    strat = DOVE;
                }
    
                players[i] = CreatePlayer(strat);
            }
    
    
            AddConnection(&players[0], &players[1]);
            AddConnection(&players[2], &players[1]);
            AddConnection(&players[0], &players[2]);
    
            int connectionCount = 6;
    
            for (int i = 3; i < playerCount; i++)
            {
                int index = rand() % connectionCount;
    
                for (int j = 0; j < playerCount; j++)
                {
                    index -= players[j].neighborCount;
                    if (index <= 0)
                    {
                        AddConnection(&players[i], &players[j]);
                        connectionCount += 2;
                    }
                }
            }
    
    
            int doves = 0;
            int hawks = 0;
            int maxConnections = 0;
    
            for (int i = 0; i < playerCount; i++)
            {
                if (players[i].strat == HAWK)
                {
                    hawks += 1;
                }
                else
                {
                    doves += 1;
                }
                if (players[i].neighborCount > maxConnections)
                {
                    maxConnections = players[i].neighborCount;
                }
            }
    
            int* connections = (int*)malloc(sizeof(int) * maxConnections); //connection[x] is the count of players with x connections
    
            for (int i = 0; i < maxConnections; i++)
            {
                connections[i] = 0;
            }
            printf("START: Doves: %i, hawks: %i \n", doves, hawks);
    
            for (int i = 0; i < gameCount; i++)
            {
                int index = rand() % playerCount;
                PlayPlayer(&players[index], prize, hawkWinningMultiplier);
            }
            doves = 0;
            hawks = 0;
    
            for (int i = 0; i < playerCount; i++)
            {
                if (players[i].strat == HAWK)
                {
                    hawks += 1;
                }
                else
                {
                    doves += 1;
                }
                connections[players[i].neighborCount] += 1;
            }
            printf("END: Doves: %i, hawks: %i \n", doves, hawks);
    
            FILE* fp;
            fp = fopen("mode4_connectioncount.csv", "w");
    
            fprintf(fp, "connection count; number of players;\n");
    
            for (int i = 0; i < maxConnections; i++)
            {
                fprintf(fp, "%i; %i;\n", i, connections[i]);
            }
            fclose(fp);
    
            return ((double)doves) / (doves + hawks);
    
    }
    
    void testGameCount(double prize, int gameCount, double hawkMultiplier, int playerCount, int repetitionCount)
    {
        double* averages = (double*)malloc(gameCount * sizeof(double));
    
        for (int i = 0; i < gameCount; i++)
        {
            double result = 0;
    
            for (int j = 0; j < repetitionCount; j++)
            {
                result += game(prize, i + 1, hawkMultiplier, playerCount);
            }
    
            result = result / repetitionCount;
    
            result = result / repetitionCount;
            averages[i] = result;
        }
    
        FILE* fp;
        char buf[30];
        snprintf(buf, 30, "mode1_gameCountTest.csv");
        fp = fopen(buf, "w");
    
        fprintf(fp, "game count; percentage of doves;\n");
    
        for (int i = 0; i < gameCount; i++)
        {
            fprintf(fp, "%i; %f;\n", i + 1, averages[i]);
        }
        fclose(fp);
    }
    
    void testPrizeAmount(double prize, int gameCount, double hawkMultiplier, int playerCount, int repetitionCount)
    {
        double* averages = (double*)malloc(gameCount * sizeof(double));
    
        int x = 0;
        for (double i = 0; i < prize; i += 0.1, x++)
        {
            double result = 0;
    
            for (int j = 0; j < repetitionCount; j++)
            {
                result += game(i, gameCount, hawkMultiplier, playerCount);
            }
    
            result = result / repetitionCount;
    
            result = result / repetitionCount;
            averages[x] = result;
        }
    
        FILE* fp;
        char buf[30];
        snprintf(buf, 30, "mode1_PrizeAmountTest.csv");
        fp = fopen(buf, "w");
    
        fprintf(fp, "prize amount; percentage of doves;\n");
    
        x = 0;
        for (double i = 0; i < prize; i += 0.1, x++)
    
            fprintf(fp, "%f; %f;\n", (double)i / 10, averages[x]);
    
        fclose(fp);
    }
    
    
    void testPlayerCount(double prize, int gameCount, double hawkMultiplier, int playerCount, int repetitionCount)
    {
        double* averages = (double*)malloc((playerCount - 1) * sizeof(double));
    
        for (int i = 1; i < playerCount; i++)
        {
            double result = 0;
    
            for (int j = 0; j < repetitionCount; j++)
            {
                result += game(prize, gameCount, hawkMultiplier, i);
            }
    
            result = result / repetitionCount;
    
            result = result / repetitionCount;
            averages[i] = result;
        }
    
        FILE* fp;
        char buf[30];
        snprintf(buf, 30, "mode1_playerCountTest.csv");
        fp = fopen(buf, "w"); //Saving data to file
    
        fprintf(fp, "player count; percentage of doves;\n");
    
        for (int i = 0; i < playerCount; i++)
        {
            fprintf(fp, "%i; %f;\n", i + 1, averages[i]);
        }
        fclose(fp);
    }
    
    int main()
    {
        const int repetitionCount = 20;
    
        double prize = 1.0;
        int gameCount = 50;
        double hawkMultiplier = 1.5;
        int playerCount = 50;
    
        testGameCount(prize, gameCount, hawkMultiplier, playerCount, repetitionCount);
        testPrizeAmount(prize, gameCount, hawkMultiplier, playerCount, repetitionCount);
        testPlayerCount(prize, gameCount, hawkMultiplier, playerCount, repetitionCount);
    
    
        return 0;
    }
    Last edited by bar12; 05-17-2020 at 12:15 PM.

  4. #4
    Registered User
    Join Date
    May 2020
    Posts
    3
    It's still not working.

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,163
    At first glance, it seems most of your memory allocations are broken.
    Code:
    $ valgrind ../a.out
    ==13564== Memcheck, a memory error detector
    ==13564== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
    ==13564== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
    ==13564== Command: ../a.out
    ==13564== 
    START: Doves: 22, hawks: 28 
    ==13564== Invalid read of size 4
    ==13564==    at 0x401285: game (bar.c:237)
    ==13564==    by 0x4013F9: testGameCount (bar.c:266)
    ==13564==    by 0x4019CE: main (bar.c:367)
    ==13564==  Address 0x56774bc is 0 bytes after a block of size 204 alloc'd
    ==13564==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==13564==    by 0x40112A: game (bar.c:211)
    ==13564==    by 0x4013F9: testGameCount (bar.c:266)
    ==13564==    by 0x4019CE: main (bar.c:367)
    ==13564== 
    ==13564== Invalid write of size 4
    ==13564==    at 0x40128A: game (bar.c:237)
    ==13564==    by 0x4013F9: testGameCount (bar.c:266)
    ==13564==    by 0x4019CE: main (bar.c:367)
    ==13564==  Address 0x56774bc is 0 bytes after a block of size 204 alloc'd
    ==13564==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==13564==    by 0x40112A: game (bar.c:211)
    ==13564==    by 0x4013F9: testGameCount (bar.c:266)
    ==13564==    by 0x4019CE: main (bar.c:367)
    ==13564==
    Start checking how you use the memory you allocate.




    And it leaks like a sieve.
    Code:
    ==13564== LEAK SUMMARY:
    ==13564==    definitely lost: 352,068 bytes in 1,883 blocks
    ==13564==    indirectly lost: 11,001,520 bytes in 33,050 blocks
    ==13564==      possibly lost: 3,221,968 bytes in 9,712 blocks
    ==13564==    still reachable: 3,041,412,992 bytes in 18,801 blocks
    3GB of leaked memory - wtf.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Registered User
    Join Date
    Apr 2019
    Posts
    58
    Well I would fix these for sure:

    Code:
    if (plyr->neighbors[i]->strat == HAWK)
    {
    }
    else
    {
        value += prize;
    }
    Instead of an empty block, I would just reverse the evaluated statement:

    Code:
    if (plyr->neighbors[i]->strat != HAWK)
        value += prize;

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,163
    Code:
            int doves = 0;
            int hawks = 0;
            int maxConnections = 0;
    
            for (int i = 0; i < playerCount; i++)
            {
                if (players[i].strat == HAWK)
                {
                    hawks += 1;
                }
                else
                {
                    doves += 1;
                }
                if (players[i].neighborCount > maxConnections)
                {
                    maxConnections = players[i].neighborCount;
                }
            }
    
            int* connections = (int*)malloc(sizeof(int) * maxConnections); //connection[x] is the count of players with x connections
    
            for (int i = 0; i < maxConnections; i++)
            {
                connections[i] = 0;
            }
            printf("START: Doves: %i, hawks: %i \n", doves, hawks);
    
            for (int i = 0; i < gameCount; i++)
            {
                int index = rand() % playerCount;
                PlayPlayer(&players[index], prize, hawkWinningMultiplier);
            }
            doves = 0;
            hawks = 0;
    
            for (int i = 0; i < playerCount; i++)
            {
                if (players[i].strat == HAWK)
                {
                    hawks += 1;
                }
                else
                {
                    doves += 1;
                }
                connections[players[i].neighborCount] += 1;
            }
            printf("END: Doves: %i, hawks: %i \n", doves, hawks);
    So, running the code under the watchful eye of valgrind, and attached to GDB whenever there is a problem.
    Code:
    Program received signal SIGTRAP, Trace/breakpoint trap.
    0x0000000000401285 in game (prize=1, gameCount=1, hawkWinningMultiplier=1.5, playerCount=50) at bar.c:237
    237	            connections[players[i].neighborCount] += 1;
    (gdb) p i
    $1 = 12
    (gdb) p players[i].neighborCount 
    $2 = 51
    (gdb) bt
    #0  0x0000000000401285 in game (prize=1, gameCount=1, hawkWinningMultiplier=1.5, playerCount=50) at bar.c:237
    #1  0x00000000004013fa in testGameCount (prize=1, gameCount=50, hawkMultiplier=1.5, playerCount=50, repetitionCount=20) at bar.c:266
    #2  0x00000000004019cf in main () at bar.c:367
    (gdb) list 211,237
    211	        int* connections = (int*)malloc(sizeof(int) * maxConnections); //connection[x] is the count of players with x connections
    212	
    213	        for (int i = 0; i < maxConnections; i++)
    214	        {
    215	            connections[i] = 0;
    216	        }
    217	        printf("START: Doves: %i, hawks: %i \n", doves, hawks);
    218	
    219	        for (int i = 0; i < gameCount; i++)
    220	        {
    221	            int index = rand() % playerCount;
    222	            PlayPlayer(&players[index], prize, hawkWinningMultiplier);
    223	        }
    224	        doves = 0;
    225	        hawks = 0;
    226	
    227	        for (int i = 0; i < playerCount; i++)
    228	        {
    229	            if (players[i].strat == HAWK)
    230	            {
    231	                hawks += 1;
    232	            }
    233	            else
    234	            {
    235	                doves += 1;
    236	            }
    237	            connections[players[i].neighborCount] += 1;
    (gdb) p maxConnections 
    $3 = 51
    (gdb) p *connections@51
    $4 = {0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 <repeats 15 times>, 5, 1, 0}
    (gdb) p playerCount
    $5 = 50
    (gdb) p players[i]
    $6 = {strat = DOVE, neighbors = 0x5576e40, neighborCount = 51}
    (gdb) p *players[i].neighbors@51
    $7 = {0x550d258, 0x550d270, 0x550d288, 0x550d2a0, 0x550d2b8, 0x550d2e8, 0x550d210, 0x550d228, 0x550d240, 0x550d2d0, 0x550d300, 0x550d318, 0x550d330, 0x550d330, 
      0x550d348, 0x550d360, 0x550d378, 0x550d390, 0x550d3a8, 0x550d3c0, 0x550d3d8, 0x550d3f0, 0x550d408, 0x550d420, 0x550d438, 0x550d450, 0x550d468, 0x550d480, 0x550d498, 
      0x550d4b0, 0x550d4c8, 0x550d4e0, 0x550d4f8, 0x550d510, 0x550d528, 0x550d540, 0x550d558, 0x550d570, 0x550d588, 0x550d5a0, 0x550d5b8, 0x550d5d0, 0x550d5e8, 0x550d600, 
      0x550d618, 0x550d630, 0x550d648, 0x550d660, 0x550d678, 0x550d690, 0x550d6a8}
    (gdb) p *players@playerCount
    $8 = {{strat = HAWK, neighbors = 0x5567470, neighborCount = 3}, {strat = DOVE, neighbors = 0x55676e0, neighborCount = 3}, {strat = HAWK, neighbors = 0x5567990, 
        neighborCount = 4}, {strat = HAWK, neighbors = 0x551b910, neighborCount = 49}, {strat = HAWK, neighbors = 0x55286a0, neighborCount = 48}, {strat = DOVE, 
        neighbors = 0x5535ac0, neighborCount = 48}, {strat = DOVE, neighbors = 0x5542fd0, neighborCount = 48}, {strat = HAWK, neighbors = 0x5550aa0, neighborCount = 48}, {
        strat = DOVE, neighbors = 0x5600f40, neighborCount = 23}, {strat = HAWK, neighbors = 0x5560ff0, neighborCount = 48}, {strat = DOVE, neighbors = 0x55b7670, 
        neighborCount = 32}, {strat = HAWK, neighbors = 0x56014a0, neighborCount = 12}, {strat = DOVE, neighbors = 0x5576e40, neighborCount = 51}, {strat = HAWK, 
        neighbors = 0x560fa90, neighborCount = 28}, {strat = HAWK, neighbors = 0x55b87d0, neighborCount = 35}, {strat = HAWK, neighbors = 0x55c6ed0, neighborCount = 31}, {
        strat = HAWK, neighbors = 0x5595270, neighborCount = 45}, {strat = HAWK, neighbors = 0x565b390, neighborCount = 23}, {strat = DOVE, neighbors = 0x566edd0, 
        neighborCount = 20}, {strat = HAWK, neighbors = 0x55a6b10, neighborCount = 48}, {strat = DOVE, neighbors = 0x55b6780, neighborCount = 48}, {strat = DOVE, 
        neighbors = 0x566f640, neighborCount = 19}, {strat = DOVE, neighbors = 0x55c64f0, neighborCount = 48}, {strat = HAWK, neighbors = 0x55d30a0, neighborCount = 43}, {
        strat = DOVE, neighbors = 0x55e3c30, neighborCount = 34}, {strat = DOVE, neighbors = 0x564a7d0, neighborCount = 26}, {strat = DOVE, neighbors = 0x563b880, 
        neighborCount = 30}, {strat = DOVE, neighbors = 0x5664e20, neighborCount = 25}, {strat = HAWK, neighbors = 0x55eeae0, neighborCount = 41}, {strat = DOVE, 
        neighbors = 0x55f9b20, neighborCount = 41}, {strat = HAWK, neighbors = 0x561de80, neighborCount = 35}, {strat = HAWK, neighbors = 0x560eef0, neighborCount = 48}, {
        strat = HAWK, neighbors = 0x561c3d0, neighborCount = 46}, {strat = DOVE, neighbors = 0x5626860, neighborCount = 41}, {strat = HAWK, neighbors = 0x562eb30, 
        neighborCount = 38}, {strat = HAWK, neighbors = 0x5670010, neighborCount = 32}, {strat = DOVE, neighbors = 0x5637550, neighborCount = 40}, {strat = HAWK, 
        neighbors = 0x56661b0, neighborCount = 33}, {strat = DOVE, neighbors = 0x56444f0, neighborCount = 47}, {strat = HAWK, neighbors = 0x5654fa0, neighborCount = 37}, {
        strat = HAWK, neighbors = 0x56743e0, neighborCount = 34}, {strat = HAWK, neighbors = 0x5652eb0, neighborCount = 47}, {strat = DOVE, neighbors = 0x565a590, 
        neighborCount = 43}, {strat = HAWK, neighbors = 0x5662f80, neighborCount = 47}, {strat = DOVE, neighbors = 0x566a9c0, neighborCount = 47}, {strat = DOVE, 
        neighbors = 0x566df00, neighborCount = 41}, {strat = HAWK, neighbors = 0x5674eb0, neighborCount = 38}, {strat = HAWK, neighbors = 0x5673370, neighborCount = 47}, {
        strat = DOVE, neighbors = 0x5676030, neighborCount = 44}, {strat = HAWK, neighbors = 0x5677240, neighborCount = 45}}
    Basically, you calculation of maxConnections is off by 1.
    If your max is 3, and you subsequently try to use [3] as an index into an array, you would need an array of length 4.

    Also, your first big memory leak is not calling free(connections) at the end of this loop.

    Second Issue
    =========

    Code:
    Program received signal SIGTRAP, Trace/breakpoint trap.
    0x0000000000400b5d in AddConnection (plyr1=0x6766ca0, plyr2=0x6766cb8) at bar.c:85
    85	    tmp = (struct player**)malloc(sizeof(struct player) * (plyr2->neighborCount + 1));
    (gdb) bt
    #0  0x0000000000400b5d in AddConnection (plyr1=0x6766ca0, plyr2=0x6766cb8) at bar.c:85
    #1  0x0000000000400f8d in game (prize=1, gameCount=50, hawkWinningMultiplier=1.5, playerCount=1) at bar.c:169
    #2  0x0000000000401822 in testPlayerCount (prize=1, gameCount=50, hawkMultiplier=1.5, playerCount=50, repetitionCount=20) at bar.c:337
    #3  0x0000000000401a2b in main () at bar.c:371
    (gdb) list
    80	    }
    81	
    82	    free(tmp);
    83	
    84	
    85	    tmp = (struct player**)malloc(sizeof(struct player) * (plyr2->neighborCount + 1));
    86	
    87	    for (int i = 0; i < plyr2->neighborCount; i++)
    88	    {
    89	        tmp[i] = (plyr2->neighbors[i]);
    (gdb) up
    #1  0x0000000000400f8d in game (prize=1, gameCount=50, hawkWinningMultiplier=1.5, playerCount=1) at bar.c:169
    169	        AddConnection(&players[0], &players[1]);
    (gdb) list
    164	
    165	            players[i] = CreatePlayer(strat);
    166	        }
    167	
    168	
    169	        AddConnection(&players[0], &players[1]);
    170	        AddConnection(&players[2], &players[1]);
    171	        AddConnection(&players[0], &players[2]);
    172	
    173	        int connectionCount = 6;
    You start with only 1 player (the parameter), but blindly assume you start with at least 3.


    Your AddConnection() function should be split, because you do the same thing twice.
    Code:
    bool AddConnections(struct player* plyr1, struct player* plyr2) {
        AddConnection(plyr1, plyr2);
        AddConnection(plyr2, plyr1);
    }
    > tmp = (struct player**)malloc(sizeof(struct player) * (plyr1->neighborCount + 1));
    1. There's no need to cast malloc in a C program.
    2. The size is wrong, it should be sizeof(struct player*), since tmp is a **.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Code problem or compiler problem....?
    By miloki in forum C Programming
    Replies: 4
    Last Post: 03-05-2015, 12:48 AM
  2. help with code problem
    By Jayb in forum C++ Programming
    Replies: 5
    Last Post: 05-17-2011, 09:59 AM
  3. code problem
    By dikumar2000 in forum C Programming
    Replies: 5
    Last Post: 10-09-2009, 01:15 AM
  4. problem with this code....
    By Huskar in forum C Programming
    Replies: 0
    Last Post: 03-30-2009, 10:38 AM
  5. Problem with some code
    By zacpack in forum C Programming
    Replies: 5
    Last Post: 03-17-2002, 06:01 PM

Tags for this Thread