【发布时间】:2021-11-13 21:03:34
【问题描述】:
谁能解释我为什么会收到此错误以及如何纠正它?
#include<stdio.h>
#include<stdlib.h>
char makemeunique(char *s,int l)
{
char *xp=(char *)malloc(l*sizeof(char));
int *pp=xp;
for(int i=1;i<l; i++)
{
int yes=0;
for(int j=i-1;j>=0; j--)
{
if(s[i]==s[j])
yes=1;
}
if(yes-1)
*pp++=s[i];
}
*pp='\0';
printf("%s\n",xp);
return xp;
}
主要功能
int main()
{
char s[9999],x [9999];
scanf("%s\n%s",s,x);
char *p1, *p2;
p1=makemeunique(s, strlen(s));
p2=makemeunique(x, strlen(x));
}
我的输出:
Hello: malloc.c:2385: sysmalloc: Assertion (old_top == initial_top (av) && old_size == 0) || ((uns igned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pa gesize - 1)) == 0)' failed. Aborted (core dumped)
这个输出是什么意思??
这个程序简单地获取两个字符串并调用函数并将创建的堆数组存储在指针中。
【问题讨论】:
-
strlen返回的长度不包含空终止符。分配内存的时候一定要记得给它增加空间。否则,空终止符将被写入分配的内存范围之外,您将有未定义的行为。 -
是的,但是如果输出字符串与输入字符串的长度相同,那么您没有
malloc足够的空间用于终止字符。需要malloc(l+1); -
我还建议您借此机会学习如何使用 调试器 来捕获崩溃和类似事件,以及如何定位代码中发生的位置,以及那时如何检查变量。
-
为什么
pp是int*? -
@John3136 哦,这绝对是个大问题!并且编译器应该能够捕获并发出警告。
标签: arrays c pointers runtime-error malloc