请教,这段代码到底错在哪了?

提出问题 解决问题 2006-05-22 07:24:14
下边这段代码,在vc中运行的时候会弹出一个错误的对话框。请帮忙指出错误的所在。谢谢。


#include <stdio.h>
#include <stdlib.h>

int *abcd(int *integer)
{
int i;

printf("请输入数组内整数的个数\n");
scanf("%d",integer);
printf("输入数组元素。\n");
realloc(integer,*integer+1);
printf("空间分配完了\n");
for (i=1;i<*integer+1;i++)
{
printf("输入:");
scanf("%d",integer+i);
}
return integer;
}

main()
{
int *integer;
integer=malloc(sizeof(int));
free(abcd(integer));
}

...全文
185 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
yingge 2006-05-23
  • 打赏
  • 举报
回复
C语言中的malloc的返回值,是不用显示的进行强制转换的。

请教楼主这句话的出处,我怎么看malloc函数的原型也觉得无法同意
triace_zhang 2006-05-23
  • 打赏
  • 举报
回复
networkhunter(土豆土豆我是地瓜) ( ) 信誉:100 2006-5-22 20:32:16 得分: 0
楼上的回答不正确。

C语言中的malloc的返回值,是不用显示的进行强制转换的。

即使我改成像你所说的那样,

错误还是存在。

下面是弹出错误对话框上所显示的信息:
debug error!
program:E:\abc\debug\abc.exe
DAMAGE:after Normal block (#41) at 0x00430200.
(press retry to debug the application)
=========================================================
汗,这是vc6编译器本身对c里free和realloc支持的问题,你换个dev c++再编译试试。

zjp1983 2006-05-23
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <stdlib.h>

int *abcd(int *integer)
{
int i;

printf("请输入数组内整数的个数\n");
scanf("%d",integer);
printf("输入数组元素。\n");
int num = *integer+1;
integer = realloc(integer,num * sizeof(int));
printf("空间分配完了\n");
for (i=1;i<num;i++)
{
printf("输入:");
scanf("%d",integer+i);
}
return integer;
}

main()
{
int *integer;
integer=malloc(sizeof(int));
free(abcd(integer));
}
hehuaiwen 2006-05-23
  • 打赏
  • 举报
回复
realloc(integer,*integer+1);语句应该有一个返回值,否则integer不会改变的。
另外,realloc的第二个参数应该为_msize(integer) + sizeof(int)*(*integer);才能保证分配到相应的内存。
_msize(*p)是返回*p分配到内存大小的函数。

由于以前的语句的错误,导致分配到的空间的大小不能装入后面的数,所以产生不能写入的错误。

integer = realloc(integer,*integer+1);
改为
integer =(int*) realloc(integer,_msize(integer) + sizeof(int)*(*integer));
即可。

该程序已经通过测试,环境为VC6.0
其中显示的为数组每个数的开始地址。


测试结果如下:
请输入数组内整数的个数
输入数组元素:
空间分配完了, sizeof(integer) is 20
start in 4397536

输入:1
position in 4397540

输入:2
position in 4397544

输入:3
position in 4397548

输入:4
position in 4397552
4allocate is over!!Press any key to continue
i_noname 2006-05-22
  • 打赏
  • 举报
回复
free失败的原因吧
integer = realloc(integer,*integer+1);
  • 打赏
  • 举报
回复
楼上的回答不正确。

C语言中的malloc的返回值,是不用显示的进行强制转换的。

即使我改成像你所说的那样,

错误还是存在。

下面是弹出错误对话框上所显示的信息:
debug error!
program:E:\abc\debug\abc.exe
DAMAGE:after Normal block (#41) at 0x00430200.
(press retry to debug the application)
triace_zhang 2006-05-22
  • 打赏
  • 举报
回复
int main()
{
int *integer;
integer=malloc(sizeof(int));//改为integer= (int*) malloc(sizeof(int));

要强制转换一下.

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧