Home > Back-end >  C Heap buffer overflow even if I use free() and unexpected for() break
C Heap buffer overflow even if I use free() and unexpected for() break

Time:12-07

I want to create text cleaner for homework, but when I start programs with address sanitiser I have heap-buffer-overflow exception even if I use free(). The second problem is that my for() cycle stops when I it sees ' '

expected output:

he3llo world
helloworld

real output:

he3llo world
hello

Thanks in advance for any answer!

My code:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char* fix_text(char* data, int len)
{
    char* fixed_message = malloc (len * sizeof(char));
    int offset = 0; //used for correct parse
    for (int i = 0; i < len; i  )
    {
        
        if (isalpha(data[i]))
        {
            
            fixed_message[offset] = data[i];
            offset  ; 
        }
        
        else if(data[i] == '\0')
        {
            break;
        }
        else if(data[i] == ' ')
        {
            continue;
        }
    }
    return fixed_message;
}
int main()
{
    char * text = malloc(100 * sizeof(char));
    scanf("%s", text);
    char* result = fix_text(text, 100);
    printf("%s\n", result);
    free(text);
    free(result);
    return 0;
}

CodePudding user response:

Your problem with the code outputting just hello is not associated with the cycle stopping. It is because your scanf is only reading until the space. So the string text you are passing to your function is basically only hello. You can fix that by using

scanf("%[^\n]s",text);

to read until the new line. For more details you can see this question

Also as @Jabberwocky has pointed out, you are not terminating your fixed message. You can just add the null terminator \0 at the end of your fixed message when you're encountering the same in your original message instead of just breaking

else if(data[i] == '\0')
{
    fixed_message[offset] = data[i];
    break;
}
  •  Tags:  
  • c
  • Related