Search code examples
cstringfree

Why does freeing the dynamically allocated memory create issue here?


I have this code:

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

char* creatString();
void printWordsThatStartWithLETTER(char letter, char *str);

void main()
{
    char *strEx1;
    char letter;
    strEx1=creatString();
    printf("Enter a letter:\n");
    scanf("%c",&letter);
    printWordsThatStartWithLETTER(letter, strEx1);
    free(strEx1);
}

char* creatString()
{
    char *str, *strTemp;
    int size;
    strTemp=(char*)malloc(256);
    printf("enter your string:\n");
    flushall();
    gets(strTemp);
    size = strlen(strTemp);
    str=(char*)malloc(size);
    strcpy(str,strTemp);
    //puts(str);
    free(strTemp);
    return str;
}
void printWordsThatStartWithLETTER(char letter, char *str)
{
    int sizeOfStrinf, i;
    sizeOfStrinf = strlen(str);
    for(i=0;i<sizeOfStrinf;i++)
    {
        if((str[i]==letter)||(str[i]==letter-32))
        {
            if(i==0)
            {
                while(str[i]!=32)
                {
                    printf("%c",str[i]);
                    i++;
                }
                printf("\n");
            }
            else
                if(str[i-1]==32)
                {
                    while(str[i]!=32)
                    {
                        printf("%c",str[i]);
                        i++;
                    }
                    printf("\n");
                }
        }
    }
}

it wont free strEx1, I have overflow. How can I free strEx1 properly?


Solution

  • You are allocating memory that is one byte too short. Add one

    size = strlen(strTemp);    
    str=(char*)malloc(size+1);
    

    or instead of strcpy use strncpy

    size = strlen(strTemp);
    str=(char*)malloc(size);
    strncpy(str,strTemp,size);
    

    The strncpy function copies the initial count characters of strSource to strDest and returns strDest. If count is less than or equal to the length of strSource, a null character is not appended automatically to the copied string. If count is greater than the length of strSource, the destination string is padded with null characters up to length count. The behavior of strncpy is undefined if the source and destination strings overlap