【问题标题】:What kind of error is this sysmalloc: Assertion?这个 sysmalloc: Assertion 是什么样的错误?
【发布时间】: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);
  • 我还建议您借此机会学习如何使用 调试器 来捕获崩溃和类似事件,以及如何定位代码中发生的位置,以及那时如何检查变量。
  • 为什么ppint*
  • @John3136 哦,这绝对是个大问题!并且编译器应该能够捕获并发出警告。

标签: arrays c pointers runtime-error malloc


【解决方案1】:

您在以下位置创建了错误的指针类型:

int *pp=xp;

pp 应该是 char* :每次执行 *pp++ 时都添加 sizeof(int) 而不是 sizeof(char) :结果是您超出分配给 xp 的内存,这可能导致通常的 C 未定义行为。

【讨论】:

  • 知道错误的含义是什么吗??
  • 正如我所写的“未定义的行为”可以是任何东西。您在分配的内存结束后设置了一个内存位置,那么任何事情都可能发生。在这种情况下,没有必要了解 malloc 中发生了什么。如果你愿意,你可以检查它的源代码,但这可能是浪费时间。
  • 是的,现在我明白了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-13
  • 2017-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多