Search code examples
cstructfree

c programming free in a own function


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Mage{
    int power;
    char* name;
}typedef Mage;

void print(Mage* mage){
    printf("Mage: %s, Power: %i", mage->name, mage->power);
}

Mage create(char name[],int power){
    Mage* mage = malloc(sizeof(Mage));
    mage->power = power;
    mage->name = name;
    printf("New Mage!\n");
    return *mage;
}

void delete(Mage* mage){
    free(mage); // -> this is not working
    // how can I use free in an own function
    // I don't want to write free in main
}

int main() {

    Mage gandalf = create("Gandalf",50);
    print(&gandalf);
    delete(&gandalf);

    printf("\n\n\n");
    return 0;
}

how can I use free in an own function, I don't want to write free in main, this source code contains a free, this program crashes

Does anyone have an idea?


Solution

  • I think the main problem with your approach here is that you are in fact returning a Mage struct in your create function, not a pointer to a Mage struct.

    That means that Mage gandalf in main is not actually at the same address as the Mage allocated by malloc in create.

    If instead you would return Mage (meaning the address) in create, and then would declare gandalf as a Mage* (a pointer to a Mage struct), you could then use gandalf directly (without &) in your print and delete function and it would refer to the same Mage you allocated in create originally.

    If it's not clear, I'm confident you should reread chapters pointers if you've been reading a C tutorial.

    Hope this helped, good luck :)