[英]C Heap buffer overflow even if I use free() and unexpected for() break
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()
.我想为家庭作业创建文本清理器,但是当我使用地址清理器启动程序时,即使我使用
free()
也会出现heap-buffer-overflow
异常。 The second problem is that my for()
cycle stops when I it sees ' '
第二个问题是我
for()
循环在我看到' '
时停止
expected output:预期 output:
he3llo world
helloworld
real output:真正的 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;
}
Your problem with the code outputting just hello
is not associated with the cycle stopping.您的代码仅输出
hello
的问题与循环停止无关。 It is because your scanf
is only reading until the space.这是因为您的
scanf
只读取到空格。 So the string text
you are passing to your function is basically only hello
.因此,您传递给 function 的字符串
text
基本上只有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.同样正如@Jabberwocky 指出的那样,您并没有终止您的固定消息。 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当您在原始消息中遇到相同的问题时,您可以在固定消息的末尾添加 null 终止符
\0
而不仅仅是中断
else if(data[i] == '\0')
{
fixed_message[offset] = data[i];
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.