如何在 c 中重置分配的内存和资源?
How to reset allocated memory and resources in c?
我的程序包含一个菜单,您可以在其中 select 2 个选项中的 1 个。
第二个只是退出程序。但是,第一个是您可以在包含 100.000 行的单独“.txt”文件中找到您选择的特定位序列的地方。
它第一次做我想要的,然后 returns 到菜单。
问题出在用户进行第二次(或多次)搜索时。该程序在屏幕上打印随机信息。
好像我在第一次搜索时没有对资源、内存或值进行 "reset"。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char ID[8];
char content[2048];
int distance;
} DATA;
void search(){
FILE *f;
DADO *z=NULL;
long int tot=0;
int a;
int c;
int i;
int j=1;
int k=0;
char e;
char b[2048];
printf("\n");
f=fopen("DANGER_DB_LARGE.txt", "r");
printf("\n");
printf("How many results do you wish?\n");
scanf("%d",&a);
printf("Introduce the sequence:\n");
scanf("%s",b);
c=strlen(b);
printf("\n");
z=(DATA*)realloc(z,(++tot)*sizeof(DATA));
while(e!=EOF){
e=fgetc(f);
if(k<8){
z[tot-1].ID[k]=e;
}
else if(k==8 && e=='\t'){
continue;
}
else if(k>=9 && e!='\n'){
z[tot-1].content[k-9]=e;
}
else if(e=='\n'){
k=(-1);
z=(DATA*)realloc(z,(++tot)*sizeof(DATA));
}
k++;
}
for(i=1; i<=tot; i++){
distance(z,i,c,b);
}
free(z);
fclose(f);
}
我继续存储这 100.000 行文本中每一行的 ID 和内容。我通过执行 free(z) 来结束函数,但是当我再次搜索时,程序只会打印随机内容。
Realoc returns void 顺便说一句
void *realloc(void *ptr, size_t size)
加上它需要一个指针作为输入,因此它通过引用传递。
update:这个函数returns指向新分配内存的指针,如果请求失败则为NULL。
我的错。
在没有中间赋值的情况下使用未初始化的变量是未定义的行为。 可能会在每个月的第一个星期三,第一次通过循环,只有当老板在看的时候,...
int e; // originally was char
//...
while (e != EOF) { // uninitialised, no intervening assignment
我的程序包含一个菜单,您可以在其中 select 2 个选项中的 1 个。 第二个只是退出程序。但是,第一个是您可以在包含 100.000 行的单独“.txt”文件中找到您选择的特定位序列的地方。
它第一次做我想要的,然后 returns 到菜单。
问题出在用户进行第二次(或多次)搜索时。该程序在屏幕上打印随机信息。 好像我在第一次搜索时没有对资源、内存或值进行 "reset"。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char ID[8];
char content[2048];
int distance;
} DATA;
void search(){
FILE *f;
DADO *z=NULL;
long int tot=0;
int a;
int c;
int i;
int j=1;
int k=0;
char e;
char b[2048];
printf("\n");
f=fopen("DANGER_DB_LARGE.txt", "r");
printf("\n");
printf("How many results do you wish?\n");
scanf("%d",&a);
printf("Introduce the sequence:\n");
scanf("%s",b);
c=strlen(b);
printf("\n");
z=(DATA*)realloc(z,(++tot)*sizeof(DATA));
while(e!=EOF){
e=fgetc(f);
if(k<8){
z[tot-1].ID[k]=e;
}
else if(k==8 && e=='\t'){
continue;
}
else if(k>=9 && e!='\n'){
z[tot-1].content[k-9]=e;
}
else if(e=='\n'){
k=(-1);
z=(DATA*)realloc(z,(++tot)*sizeof(DATA));
}
k++;
}
for(i=1; i<=tot; i++){
distance(z,i,c,b);
}
free(z);
fclose(f);
}
我继续存储这 100.000 行文本中每一行的 ID 和内容。我通过执行 free(z) 来结束函数,但是当我再次搜索时,程序只会打印随机内容。
Realoc returns void 顺便说一句
void *realloc(void *ptr, size_t size)
加上它需要一个指针作为输入,因此它通过引用传递。
update:这个函数returns指向新分配内存的指针,如果请求失败则为NULL。
我的错。
在没有中间赋值的情况下使用未初始化的变量是未定义的行为。 可能会在每个月的第一个星期三,第一次通过循环,只有当老板在看的时候,...
int e; // originally was char
//...
while (e != EOF) { // uninitialised, no intervening assignment