Home > Enterprise >  This code works without free() involved. Is this okay?
This code works without free() involved. Is this okay?

Time:11-24

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

int     ft_strlen(char *str)
{
        int     i = 0;
        if (str)
                while (str[i])
                        i  ;
        return (i);
}

void    ft_append(char **str, char c)
{
        int     len = ft_strlen(*str);
        char    *str2 = *str;
        char    *newstr = malloc(len   2);
        int     i = 0;
        if (len != 0)
        {
                while (i < len)
                {
                        newstr[i] = str2[i];
                        i  ;
                }
        }
        newstr[i] = c;
        newstr[i 1] = '\0';
        *str = newstr;
//this line causes *str to also be freed.
//        free(newstr);
}

int     main()
{
        char    *str;
        ft_append(&str, 'x');
        ft_append(&str, 'y');
        ft_append(&str, 'z');
        printf("str = %s\n", str);
}

This code works as intended. Printf returns xyz. But I am wondering if it is okay for me to not use free() in ft_append? I always read that when a new array is created using malloc I should follow up with free when I am not using the array anymore, but when I type free(newstr) str also gets free resulting in Printf returning nothing.

Thank you very much for your assistance.

CodePudding user response:

For starters the program has undefined behavior because the pointer str defined in main was not initialized and has an indeterminate value.

char    *str;

So at least calling the function ft_strlen for such a pointer

int     len = ft_strlen(*str);

invokes undefined behavior.

Also the function ft_append produces memory leaks because early allocated memory the address of which is stored in the pointer str is not freed in subsequent calls of the function.

You need initially to set the pointer str to NULL

char    *str = NULL;

and within the function ft_append to use the function realloc instead of malloc.

The program can look the following way

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

size_t  ft_strlen( const char *str )
{
        size_t   i = 0;

        while ( str[i] ) i  ;

        return i;
}

int     ft_append( char **str, char c )
{
        size_t len = *str == NULL ? 0 : ft_strlen( *str );

        
        char    *newstr = realloc( *str, len   2 );

        int success = newstr != NULL;

        if ( success )
        {
            *str = newstr;
            ( *str )[len] = c;
            ( *str )[len   1] = '\0';
        }

        return success;
}

int     main( void )
{
        char    *str = NULL;

        ft_append( &str, 'x' );
        ft_append( &str, 'y' );
        ft_append( &str, 'z' );

        printf( "str = %s\n", str );

        free( str );
}

CodePudding user response:

Yes its a problem as your program will have memory leaks , where information you have put in memory will stay there even after your program has exited.

look at a program called Valgrind Website and Install it.

Run valgrind --leak-check=yes nameofyourprogram and it will indicate how much memory is leaked .

The problem is malloc() allocates memory randomly which means that once the memory leak happens its hard to trace and delete unless you restart you computer ,A lot of memory leaks can cause out of memory issues if this was a big project.

In Short

free(newstr);
newstr=NULL;

Also use ((len 2 )* sizeof(char)) Instead so the malloc is char size based

  •  Tags:  
  • c
  • Related