Search code examples
cpointersmallocfree

Deallocated memory functions C


I have problems with memory deallocation in C. Without the division of functions everything is OK, but unfortunately it does not work on the same functions. Here is the code:

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

typedef struct {
    char *name;
    enum {
        summer,
        winter
    } index;
} student;

bool init(student *s) {
    printf("The next stage in the allocation of memory\n");
    s = (student*)malloc(sizeof(*s));
    if (&s == NULL) {
        printf("Allocation Failed\n");
        return 0;
    } else {
        printf("Allocation completed successfully\n");
    }
}   

void delete(student *s) {
    if (&s != NULL) {
        printf("begin removal\n");
        free(s);
        printf("Released memory");
    }
}

int main() {
    student *s;
    init(s);
    delete(s);

    return 0;
}

I do not know what I'm doing wrong. Please help.


Solution

  • First of all the function init has undefined bbehaviour because it returns nothing in the case of successful memory allocation.

    You can check whether the memory was allocated or not by returning pointer to the allocated memory or NULL.

    Also this statement

    if(&s==NULL){
    

    is wrong. The condition will always yield false because the address of the local variable s is not equal to NULL.

    So the function can be rewritten either the following way

    student * init()
    {
        printf("The next stage in the allocation of memory\n");
    
        student *s = ( student* )malloc( sizeof( *s ) );
    
        if ( s == NULL )
        {
            printf("Allocation Failed\n");
        } 
        else 
        {
            printf("Allocation completed successfully\n");
        }
    
        return s;
    } 
    

    And called like

    int main( void )
              ^^^^^
    {
        student *s = init();
        //...
    

    Or it can be defined the following way

    int init( student **s )
    {
        printf("The next stage in the allocation of memory\n");
    
        *s = ( student* )malloc( sizeof( **s ) );
    
        int success = *s != NULL;
    
        if ( !success )
        {
            printf("Allocation Failed\n");
        } 
        else 
        {
            printf("Allocation completed successfully\n");
        }
    
        return success;
    } 
    

    and called like

    int main( void )
              ^^^^^
    {
        student *s;
        init( &s );
        //...
    

    The function delete should be defined at least like

    void delete(student *s) {
        if (s != NULL) {
           ^^^
            printf("begin removal\n");
            free(s);
            printf("Released memory");
        }
    }