0

I am new to malloc() and been reading my books and some tutorials about it. Now that I have written my assignment, it's required that you do not have any memory leaks.

This is a piece of my code how I have written it in main:

#define _CRTDBG_MAP_ALLOC
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <crtdbg.h>
int main()
{   
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    srand((unsigned)time(NULL)); //Kallas för randomisera ett nummer tidsmässigt
    struct CardDeck * deck; //Dynamiskt allokerad array
    int index;
    int suit_index;
    /*int i;  kan användas om man vill loopa kortleken*/
    deck = (struct CardDeck *)malloc(sizeof(struct CardDeck)); //Bör bara användas en gång med tanke på att vi bara har en pekare under vår struct i cardeck
    deck->last_Index = 0; //Pekar på senaste indexen för att se så att kortleken är full. 
    for (suit_index = 0; suit_index < NR_OF_SUITS; suit_index++)    //Loopar 4 (avser färgerna)
        for (index = 0; index < COLOR_SIZE; index++) //Loopar 13 gånger för varje värde i kortleken
        {
            deck->cards[suit_index*COLOR_SIZE + index].suit = suit_index;
            deck->cards[suit_index*COLOR_SIZE + index].value = index;
        }
    /*for (i = 0; i < 52; i++) {
    printCards(deck);
    }  Om man vill loopa igenom hela kortleken (sorterad) så finns den möjlig*/

    shuffleCards(deck->cards); 
    play(deck);
    system("pause");
    return 0;
    free(deck);
}

As you see, I used free(deck) at the bottom, is it something that I am missing or what am I doing wrong?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
William hart
  • 123
  • 5
  • 1
    Don't cast the return value of malloc - http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Idos Jan 03 '16 at 21:27
  • 1
    Why does `int main() {printf("AAA\n"); return 0; printf("BBB\n");}` print AAA but not BBB? – user253751 Jan 04 '16 at 00:00

2 Answers2

6

Your free() statement is after return, do you think it executes? You can try formatting your code carefully and then this kind of mistake might be avoided.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
1

The problem is, you attempt to call free() after the return statement.

Once the execution reach the unconditional return statement, the control will return to the caller and any statement placed after the return statement will be unreachable code. So, essentially, your call to free() does not get a chance to execute, at all.

To quote the standard, chapter §6.8.6.4

A return statement terminates execution of the current function and returns control to its caller. [...]

So basically, your free() does not get a chance o free-up the dynamically allocated memory, resulting in a memory leak.

You need to call free() before the return statement, like

. . . . 
free(deck);
return 0;
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261