源程序如下:
#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>
void main()
{
int n=30;
char *ch1,*ch2;
ch1=(char *) malloc(n*sizeof(char));
ch2=(char *) malloc(n*sizeof(char));
for(int i=0;i<n-1;i++)
ch1[i]='A';
ch1[i]='\0';
ch2=ch1;
free(ch1);
free(ch2);
}
错误提示如下:
Debug Assertion Failed!
Program: ****.exe
File: dbgheap.c
line: 1044 Expression: _CrtIsValidHeapPoint(pUserData) For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts. (Press Retry to debug the application)
编译组建都没问题,运行就有错误!如果任意去掉一个free,运行就没有问题,但是不是其中一个字符指针的空间就没释放呢?另外,用静态数组也没有问题。本人就想用动态分配内存的方法解决,因而数组下表希望通过非常量表达式确定!
#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>
void main()
{
int n=30;
char *ch1,*ch2;
ch1=(char *) malloc(n*sizeof(char));
ch2=(char *) malloc(n*sizeof(char));
for(int i=0;i<n-1;i++)
ch1[i]='A';
ch1[i]='\0';
ch2=ch1;
free(ch1);
free(ch2);
}
错误提示如下:
Debug Assertion Failed!
Program: ****.exe
File: dbgheap.c
line: 1044 Expression: _CrtIsValidHeapPoint(pUserData) For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts. (Press Retry to debug the application)
编译组建都没问题,运行就有错误!如果任意去掉一个free,运行就没有问题,但是不是其中一个字符指针的空间就没释放呢?另外,用静态数组也没有问题。本人就想用动态分配内存的方法解决,因而数组下表希望通过非常量表达式确定!
另外字符串不是这样拷贝的,用strcpy可以。
我整理了一下:
////////////////////////////////////////////////////////////////
Assert 断言处理
1、在VC安装目录下搜dbgheap.c;
2、找到1044行,看看是在哪一个函数中发生的断言,分析出错原因;
3、在你的程序中设置断点,断点跟踪一下你的代码,直到找到和错误最接近的代码口;
4、修改你的代码。
////////////////////////////////////////////////////////////////
free(ch1);
free(ch2);
ch1所指的堆内存被释放了两次。
这样就OK
free(ch2);
ch2=ch1;
free(ch1);
你说的i在循环外面是无效的,是错的!i在循环外有效,不信你可以试试!另外你说字符串不能像我那样拷贝,也不妥!eduyu兄的做法就证明了这点。但是我用strcpy赋值,运行后确实没错了,还是谢谢你!能分析一下原因就更好了:-)
iyranly兄:
先谢谢你给我提供的解决方法,但我在安装目录下没搜到dbgheap.c呀?而且你说的3与4怎么操作,我不会!能否说得再详细些?
eduyu兄:
你的做法也是可行的,谢谢你!但我觉得先ch2的内存给free了,再给它赋值是不是有些矛盾啊?
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
void main()
{
int n=30;
char *ch1,*ch2;
ch1=(char *) malloc(n*sizeof(char));
ch2=(char *) malloc(n*sizeof(char));
for(int i=0;i <n-1;i++)
ch1[i]='A';
ch1[n-1]='\0';
//ch2=ch1;
memcpy(ch2,ch1,n*sizeof(char));
free(ch1);
free(ch2);
}
这些是基础C语言知识,希望别人不要故意误导。
--------------------------------------------------------
基本概念,指针的使用,并不一定要malloc
ch2=(char*)malloc(n*sizeof(char));
ch2=ch1;
这两句都是在给指针赋值,赋一个,再赋一个替换上一个,有何意义?