C中的free()多重分配错误 [英] free() multiple allocation error in C

查看:69
本文介绍了C中的free()多重分配错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

free()C中的多个分配错误

=============================== =====


嗨!

我用C语言在PC上用C语言写了一个程序,用$ c
环境。

我在释放多个分配时出错如下:

1.我分配了一个指针数组。

2.我从文本文件中逐行读取。

3.我为读取行分配了内存。

4.我将指向malloc()的指针写入指针数组。

5.问题出在free()函数中。当我试图在

循环中释放

分配的行时,Visual C会抛出异常。

6.我想要知道为什么?。我也尝试以相反的顺序释放我

已经分配了它们,但是这也没有用。

7.有人有想法吗?

8.请将答案发送至 a.*****@solidgroup.com

9.提前致谢。

Ariel Ze''evi。


部分代码:


#include" stdafx.h"

#include< stdio.h>

#include< stdlib。 h>

#include< string.h>


#define byte unsigned char

#define word unsigned short


typedef struct {

word FlashAddress,index;

} IndexAddress;


FILE * fp;

char ** FileBuff;

IndexAddress * AddStruct;

word LinesNumber = 0;

int main(int argc,char * argv [])

{

char FileName [] = {" c:\\ariel \\flash196 \ \modbus.hex"};

char line [MAX_LINE];

long BufSize = 0;

word i,LineLen = 0;

//打开阅读(将如果文件FileName,则会失败不存在)

if((fp = fopen(FileName," r"))== NULL)

printf("文件%s未打开\ n",FileName);

else

printf("文件''%s已打开\ nn,FileName);


//查找Hex文件中的行数

while(!feof(fp))

{

fgets(line,MAX_LINE,fp);

LinesNumber ++;

}

printf(" \ nLinesNumber =%d \ n" ,LinesNumber);


//分配一个指向行数的指针数组

if((FileBuff =(char **)malloc(LinesNumber * sizeof) (char *)))== NULL)

{

printf(" malloc error!\ n");

return - 1;

}


倒带(fp);


//从文件中逐行读取,分配它的内存和复制线

分配

for(i = 0; i< LinesNumber; i ++)

{

fgets(行,MAX_LINE,fp);

if((FileBuff [i] =(char *)malloc(strlen(line)*

sizeof(char)))== NULL)

{

printf(" malloc error!\ n");

返回-1;

}

strcpy(FileBuff [ i],line);

}

//分配指向行数的指针数组

AddStruct =(IndexAddress *)malloc( LinesNumber *

sizeof(IndexAddress));

if(AddStruct == NULL)

{

printf( malloc错误!\ n);

返回-1;

}


//准备排序

for(i = 0; I< LinesNumber; i ++)

{

AddStruct [i] .FlashAddress = Address(i);

AddStruct [i] .index = i;

}

PrintAddIndex();


QuickSort(AddStruct,0,LinesNumber);

PrintAddIndex( );

for(i = 0; i< LinesNumber; i ++)

free(FileBuff [i]); < ======在这一点上该计划是

THROWN。

免费(FileBuff);


/ *关闭fp * /

if(fclose(fp))

printf("文件%s未关闭\ n,FileName);


返回0;

}

解决方案

检查你是否是试图释放之前被释放的记忆..


[snips]


4月27日星期四2006 03:15:30 -0700, a.*****@solidgroup.com 写道:

#define byte unsigned char
#define word unsigned short


不使用typedef的一些原因?

FILE * fp;
char ** FileBuff;
IndexAddress * AddStruct;
word LinesNumber = 0;

int main(int argc,char * argv [])
{
char FileName [] = {" c:\\ariel \\flash196 \\modbus.hex"};


Ick。失去大括号。

char line [MAX_LINE];
长BufSize = 0;
字i,LineLen = 0;

//打开read(如果文件FileName不存在则会失败)
if((fp = fopen(FileName," r"))== NULL)
printf("文件%s是not open\\\
",FileName);

printf("文件''%s被打开\ nn,FileName);


如果它没有打开,那么明确地处理那个

会不会更优雅,比如退出,或者其他什么?

//查找数量Hex文件中的行
while(!feof(fp)){
fgets(line,MAX_LINE,fp);
LinesNumber ++;
}


丑陋,因为它得到了eof测试低音 - ackwards。基本上,feof只有

才会真实_ after_ fgets失败,读完最后一行。

printf(" \ nLinesNumber =%d \ n", LinesNumber);

//分配一个指向行数的指针数组
if((FileBuff =
(char **)malloc(LinesNumber * sizeof(char *)) )== NULL){


在我之后重复:我们不*铸造malloc。重复五六百元b
次。如果您的编译器抱怨,那么a)您实际上正在使用

C ++,b)您忘记了所需的标题,或者c)您做错了什么。

printf(" malloc error!\ n");
返回-1;


没有像-1这样的生物。它是0,EXIT_SUCCESS或EXIT_FAILURE。

//从文件中逐行读取,为其分配内存并复制行
为分配
(i = 0 ; i< LinesNumber; i ++)
{
fgets(line,MAX_LINE,fp);
if((FileBuff [i] =(char *)malloc(strlen(line)*
sizeof(char)))== NULL)


为什么使用sizeof(char)?如果你不得不乘以7 * 3,你会把它写成(7 * 1)*(3 * 1)吗?没有?那你为什么要完全毫无意义

乘以1?提示:sizeof(char)是1. Period。因此,几乎在每种情况下你都会看到它被用来完全毫无意义。


那说,你也分配了一个几个字符。例如,如果文件中的

行是ABC \ n,那么你的行是行。变量将包含ABC \ n \\\ 0。

这是5个字符 - 但strlen只返回4;最后,它不包括\0
。所以你只需要一个字节。

strcpy(FileBuff [i],line);


然而,当你尝试

快乐写完分配区域的末尾时,这可能会很好地呕吐和死亡。

for(i = 0; i< LinesNumber; i ++)
free(FileBuff [i]); < ======在这一点上,程序是
了。




猜测,因为你的字符串都不是字符串 - 缺乏

\0 - 我怀疑你正在捣毁malloc /免费使用的数据来跟踪已分配的内容。


完全有可能你的排序程序搞砸了;

如果它正在对非字符串,坏事做基于字符串的比较将会发生


a 。***** @ solidgroup.com 写道:

free()C中的多个分配错误============== ======================

嗨!
我已用C语言在PC上用Windows 2000编写了一个程序Visual C
环境。
我在释放多个分配时出错如下:
1.我分配了一个指针数组。
2.我从文本中逐行读取档案。
3.我为读取行分配了内存。
4.我将指向malloc()的指针写入指针数组。
5.问题出在free()函数中。当我试图在
循环中释放
分配的行时,Visual C会抛出异常。
6.我想知道为什么?我也尝试以相反的顺序释放我
分配它们,但这也行不通。
7.有没有人有想法?
8.请将答案发送至 a.*****@solidgroup.com
9.提前致谢。< Ariel Ze''evi。

部分代码:

#include" stdafx.h"
#include< stdio.h>
#include< stdlib.h>
#include< string.h>

#define byte unsigned char
#define word unsigned short

typedef struct {
word FlashAddress,index;
} IndexAddress;

FILE * fp;
char ** FileBuff;
IndexAddress * AddStruct;
word LinesNumber = 0;

int main(int argc,char * argv [])
{char FileName [] = {" c: \\ariel \\flash196 \\modbus.hex"};
char line [MAX_LINE];
long BufSize = 0;
字i,LineLen = 0;

//打开阅读(将失败我f fileFileName不存在)
if((fp = fopen(FileName," r" ))== NULL)
printf(文件%s未打开\ n,文件名);

printf("文件''%s被打开) \ n",FileName);

//查找Hex文件中的行数
while(!feof(fp))
{
fgets(行) ,MAX_LINE,fp);
LinesNumber ++;
}
printf(" \ nLinesNumber =%d \ n",LinesNumber);

//分配指向行数的指针数组
if((FileBuff =(char **)malloc(LinesNumber * sizeof(char *)))== NULL)
{
printf(" malloc错误!\ n");
返回-1;
}

快退(fp);

//逐行读取文件,为其分配内存并将行复制到分配
for(i = 0; i< LinesNumber; i ++)
{
fgets(line,MAX_LINE,fp);
if((FileBuff [i] =(char *)malloc(strlen(line)*
sizeof(char)))== NULL)
{
printf(" malloc错误!\ n");
返回-1;
}
strcpy(FileBuff [i],line);
}

//分配指向行数的指针数组
AddStruct =(IndexAddress *)malloc(LinesNumber *
sizeof(IndexAddress));
if(AddStruct == NULL)
{/> printf(" malloc error!\ n");
返回-1;
}
//准备排序
(i = 0; I< LinesNumber; i ++)
{
AddStruct [i] .FlashAddress = Address(i);
AddStruct [i] .index = i;
}
PrintAddIndex();

QuickSort(AddStruct,0,LinesNumber);
PrintAddIndex();

for(i = 0; i< LinesNumber; i ++)
free( FileBuff [I]); < ======在这一点上该程序是
THROWN。
免费(FileBuff);

/ *关闭fp * /
if(fclose) (fp))
printf(文件%s未关闭\ n,文件名);

返回0;
}

1.我分配了一个指针数组
5.问题出在free()函数中。当我试图在
循环中释放
分配的行时,Visual C会抛出异常。




传递基地址指针数组应该是
释放你在步骤1中分配的整个内存(我假设你已经分配了一个大块的
)。正如有人之前发布的那样,你可能会试图两次释放相同的内存。


Rgds。

Amogh


free() multiple allocation error in C
====================================

Hi!
I have written a program in C on PC with Windows 2000 in a Visual C
environment.
I have an error in freeing multiple allocation as follows:
1. I allocated an array of pointer.
2. I Read line by line from a text file.
3. I allocated memory for the read line.
4. I wrote the pointer from malloc() to the array of pointers.
5. The problem is in the free() function. When I tried to free in a
loop the
allocated lines, the Visual C throw me with an exception.
6. I wanted to know why?. I tried also to free in the opposite order I
have
allocated them, but this also doesn''t work.
7. Does anyone has an idea?
8. Please send answer to a.*****@solidgroup.com .
9. Thanks in advance.
Ariel Ze''evi.

Parts of the code:

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define byte unsigned char
#define word unsigned short

typedef struct {
word FlashAddress, index;
} IndexAddress;

FILE *fp;
char **FileBuff;
IndexAddress *AddStruct;
word LinesNumber=0;
int main(int argc, char* argv[])
{
char FileName[]={"c:\\ariel\\flash196\\modbus.hex"};
char line[MAX_LINE];
long BufSize=0;
word i,LineLen=0;
// Open for read (will fail if file "FileName" does not exist)
if( (fp = fopen( FileName, "r" )) == NULL )
printf( "The file %s was not opened\n",FileName );
else
printf( "The file ''%s was opened\n",FileName );

// Finds Number of lines in the Hex File
while (!feof(fp))
{
fgets(line,MAX_LINE,fp);
LinesNumber++;
}
printf("\nLinesNumber=%d\n",LinesNumber);

// Allocate an array of pointers to number of lines
if((FileBuff = (char **)malloc(LinesNumber * sizeof(char *)))==NULL)
{
printf("malloc error!\n");
return -1;
}

rewind(fp);

// Read line by line from file, allocate a memory to it and copy line
to allocation
for(i=0; i<LinesNumber; i++)
{
fgets(line,MAX_LINE,fp);
if((FileBuff[i] = (char *)malloc(strlen(line) *
sizeof(char)))==NULL)
{
printf("malloc error!\n");
return -1;
}
strcpy(FileBuff[i],line);
}
// Allocate an array of pointers to number of lines
AddStruct = (IndexAddress*)malloc(LinesNumber *
sizeof(IndexAddress));
if(AddStruct ==NULL)
{
printf("malloc error!\n");
return -1;
}

// Prepare for sorting
for(i=0; i<LinesNumber; i++)
{
AddStruct[i].FlashAddress=Address(i);
AddStruct[i].index=i;
}
PrintAddIndex();

QuickSort(AddStruct,0,LinesNumber);
PrintAddIndex();
for(i=0; i<LinesNumber; i++)
free(FileBuff[i]); <====== IN THIS POINT THE PROGRAM WAS
THROWN.
free(FileBuff);

/* Close fp */
if( fclose( fp ) )
printf( "The file %s was not closed\n",FileName );

return 0;
}

解决方案

Check if u are trying to free the memory which is freed before..


[snips]

On Thu, 27 Apr 2006 03:15:30 -0700, a.*****@solidgroup.com wrote:

#define byte unsigned char
#define word unsigned short
Some reason for not using typedefs?
FILE *fp;
char **FileBuff;
IndexAddress *AddStruct;
word LinesNumber=0;
int main(int argc, char* argv[])
{
char FileName[]={"c:\\ariel\\flash196\\modbus.hex"};
Ick. Lose the braces.
char line[MAX_LINE];
long BufSize=0;
word i,LineLen=0;
// Open for read (will fail if file "FileName" does not exist)
if( (fp = fopen( FileName, "r" )) == NULL )
printf( "The file %s was not opened\n",FileName );
else
printf( "The file ''%s was opened\n",FileName );

If it doesn''t open, wouldn''t it be more graceful to handle that
explicitly, say by exiting, or whatever?
// Finds Number of lines in the Hex File
while (!feof(fp)) {
fgets(line,MAX_LINE,fp);
LinesNumber++;
}
Ugly, as it gets the eof test bass-ackwards. Basically, feof is only
going to be true _after_ fgets fails, reading past the last line.
printf("\nLinesNumber=%d\n",LinesNumber);

// Allocate an array of pointers to number of lines
if((FileBuff =
(char **)malloc(LinesNumber * sizeof(char *)))==NULL) {
Repeat after me: "We do *not* cast malloc." Repeat five or six hundred
times. If your compiler is complaining, then a) You''re actually using
C++, b) You forget a header you need, or c) you''re doing something wrong.
printf("malloc error!\n");
return -1;
No such critter as -1. It''s 0, EXIT_SUCCESS or EXIT_FAILURE.
// Read line by line from file, allocate a memory to it and copy line
to allocation
for(i=0; i<LinesNumber; i++)
{
fgets(line,MAX_LINE,fp);
if((FileBuff[i] = (char *)malloc(strlen(line) *
sizeof(char)))==NULL)
Why are you using sizeof(char)? If you had to multiply 7*3, would you
write it as (7*1) * (3*1)? No? So why are you doing completely pointless
multiplication by 1? Hint: sizeof(char) is 1. Period. Hence it''s
completely pointless in virtually every case you''ll ever see it used.

That said, you''re allocating one too few characters. For example, if your
line in the file is ABC\n, your "line" variable will contain "ABC\n\0".
That''s 5 chars - but strlen only returns 4; it doesn''t include the \0 at
the end. So you''re short one byte.
strcpy(FileBuff[i],line);
And, of course, this right here may well puke and die as you try to
merrily write past the end of the allocated region.
for(i=0; i<LinesNumber; i++)
free(FileBuff[i]); <====== IN THIS POINT THE PROGRAM WAS
THROWN.



At a guess, since none of your strings are actually strings - lacking
the \0 - I''d suspect you''re trashing the data that malloc/free use to
track what''s been allocated.

It''s also entirely possible that your sort routine is mucking things up;
if it''s doing string-based comparisons on non-strings, bad things will
happen there, too.


a.*****@solidgroup.com wrote:

free() multiple allocation error in C
====================================

Hi!
I have written a program in C on PC with Windows 2000 in a Visual C
environment.
I have an error in freeing multiple allocation as follows:
1. I allocated an array of pointer.
2. I Read line by line from a text file.
3. I allocated memory for the read line.
4. I wrote the pointer from malloc() to the array of pointers.
5. The problem is in the free() function. When I tried to free in a
loop the
allocated lines, the Visual C throw me with an exception.
6. I wanted to know why?. I tried also to free in the opposite order I
have
allocated them, but this also doesn''t work.
7. Does anyone has an idea?
8. Please send answer to a.*****@solidgroup.com .
9. Thanks in advance.
Ariel Ze''evi.

Parts of the code:

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define byte unsigned char
#define word unsigned short

typedef struct {
word FlashAddress, index;
} IndexAddress;

FILE *fp;
char **FileBuff;
IndexAddress *AddStruct;
word LinesNumber=0;
int main(int argc, char* argv[])
{
char FileName[]={"c:\\ariel\\flash196\\modbus.hex"};
char line[MAX_LINE];
long BufSize=0;
word i,LineLen=0;
// Open for read (will fail if file "FileName" does not exist)
if( (fp = fopen( FileName, "r" )) == NULL )
printf( "The file %s was not opened\n",FileName );
else
printf( "The file ''%s was opened\n",FileName );

// Finds Number of lines in the Hex File
while (!feof(fp))
{
fgets(line,MAX_LINE,fp);
LinesNumber++;
}
printf("\nLinesNumber=%d\n",LinesNumber);

// Allocate an array of pointers to number of lines
if((FileBuff = (char **)malloc(LinesNumber * sizeof(char *)))==NULL)
{
printf("malloc error!\n");
return -1;
}

rewind(fp);

// Read line by line from file, allocate a memory to it and copy line
to allocation
for(i=0; i<LinesNumber; i++)
{
fgets(line,MAX_LINE,fp);
if((FileBuff[i] = (char *)malloc(strlen(line) *
sizeof(char)))==NULL)
{
printf("malloc error!\n");
return -1;
}
strcpy(FileBuff[i],line);
}
// Allocate an array of pointers to number of lines
AddStruct = (IndexAddress*)malloc(LinesNumber *
sizeof(IndexAddress));
if(AddStruct ==NULL)
{
printf("malloc error!\n");
return -1;
}

// Prepare for sorting
for(i=0; i<LinesNumber; i++)
{
AddStruct[i].FlashAddress=Address(i);
AddStruct[i].index=i;
}
PrintAddIndex();

QuickSort(AddStruct,0,LinesNumber);
PrintAddIndex();
for(i=0; i<LinesNumber; i++)
free(FileBuff[i]); <====== IN THIS POINT THE PROGRAM WAS
THROWN.
free(FileBuff);

/* Close fp */
if( fclose( fp ) )
printf( "The file %s was not closed\n",FileName );

return 0;
}
1. I allocated an array of pointer
5. The problem is in the free() function. When I tried to free in a
loop the
allocated lines, the Visual C throw me with an exception.



Passing the base address of the pointer array should
free the entire memory you allocated in step 1 (I assume you
allocated one big chunk). As somebody posted before, you might
be trying to free the same memory twice.

Rgds.
Amogh


这篇关于C中的free()多重分配错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆