要幸福也要节制,自古红粉如

认认真真的学习,踏踏实实的走路:戒骄戒躁!!!
程序代码:if( jilu < (int)length)
{
jilu = length;
temp = buffer;
free(temp); -----------》free 掉 temp 上面的TEMP=BUFFER是干什么用的,再就是temp 是初始化过的静态数据 不是放在堆里面的 怎么个free法呀,下面又给这个temp护值为NULL,这个就无法理解了
temp = NULL;
buffer = (char*)malloc(length+1);
}
哦,本意是对buffer指向的空间进行释放,只是第一次忘记给buffer申请空间了,谢谢
程序代码:#include <stdio.h>
#include <stdlib.h>
int main(void)
{
size_t str_count = 0;
fpos_t *postition = NULL;
char *buffer = (char*)malloc(4);
size_t length = 0;
size_t jilu = 3;
char *temp = NULL;
int i = 0;
char *Input_filename = "E:\\才、\\Test\\test1.bin";
char *Out_filename = "E:\\才、\\Test\\test2.bin";
FILE *Input_pfile = NULL;
FILE *Out_pfile = NULL;
if(!(Input_pfile = fopen(Input_filename, "rb")))
{
printf("读取文件%s faild!\n",Input_filename);
return 1;
}
/* 得到字符串数目 */
while(1)
{
fread(&length, sizeof(size_t), 1, Input_pfile);
if(feof(Input_pfile))
break;
if( jilu < length)
{
jilu = length;
free(buffer);
buffer = (char*)malloc(length+1);
}
fread(buffer, sizeof(char), length, Input_pfile);
buffer[length] = '\0';
printf("buffer == %s\nlength == %d\n",buffer, length);
str_count++;
}
printf("The count of strings are %d\n",str_count);
postition = (fpos_t*)malloc(str_count-1);
rewind(Input_pfile);
fread(&length, sizeof(size_t), 1, Input_pfile);
fread(buffer, sizeof(char), length, Input_pfile);
buffer[length] = '\0';
printf("length = %d\n%s\n",length, buffer);
for(i=0;i<(int)str_count-1;i++)
{
fgetpos(Input_pfile, &postition[i]);
fread(&length, sizeof(size_t), 1, Input_pfile);
fread(buffer, sizeof(char), length, Input_pfile);
}
if(!(Out_pfile = fopen(Out_filename, "wb")))
{
printf("error!\n");
return -1;
}
for(i=0;i<(int)str_count-1;i++)
{
fsetpos(Input_pfile, &postition[str_count-2-i]);
fread(&length, sizeof(size_t), 1, Input_pfile);
fwrite(&length, sizeof(size_t), 1, Out_pfile);
fread(buffer, 1, length, Input_pfile);
fwrite(buffer, 1, length, Out_pfile);
}
rewind(Input_pfile);
fread(&length, sizeof(size_t), 1, Input_pfile);
fwrite(&length, sizeof(size_t), 1, Out_pfile);
fread(buffer, 1, length, Input_pfile);
fwrite(buffer, 1, length, Out_pfile);
fclose(Out_pfile);
fclose(Input_pfile);
Out_pfile = fopen(Out_filename, "rb");
printf("The strings in the %s are:\n",Out_filename);
for(i=0;i<(int)str_count;i++)
{
fread(&length, sizeof(size_t), 1, Out_pfile);
fread(buffer, sizeof(char), length, Out_pfile);
buffer[length] = '\0';
printf("%s\n",buffer);
}
fclose(Out_pfile);
remove(Out_filename);
return 0;
}
程序代码:size_t str_count = 0;
fpos_t *postition = NULL;
char *buffer = (char*)malloc(4);
size_t length = 0;
size_t jilu = 3;
char *temp = NULL;
int i = 0;
一旦malloc()中的值大于4(如char *buffer = (char*)malloc(5))程序就又会和先前一样出现错误
程序代码:
if( jilu < length)
{
jilu = length;
free(buffer);
buffer = (char*)malloc(length+1);
}这里都会对buffer的内存大小进行判断啊,而且无论length的值是什么,一开始buffer申请的空间还是不能超过4个字节