提问人:ItsBuddy007 提问时间:11/8/2022 更新时间:11/8/2022 访问量:51
动态结构体数组被分配到无限大
Dynamic Struct Array Being Allocated to infinite size
问:
我的任务是编写一个结构,该结构从文件中读取数据,并在需要时重新分配更多内存。 到目前为止,我已经完成了以下工作: 结构:
typedef struct myprog
{
int id;
char name[100];
int price;
}myprog;
读取功能:
myprog* readFromFile(FILE* fP, char fileName[], myprog* reg, int* size)
{
fP = fopen(fileName, "r"); //Open Input File as read
if (fP == NULL) //If File is not found, do nothing
{
printf("File does not exist.");
}
else //Else read file line by line
{
printf("\nReading from File");
int x = 0;
char line[100];
char* split;
char* args[4];
while (fgets(line, 100, fP)) //Read the first line
{
if (x == MAX) //If Max Size is reached, increase it twice
{
int new_size = MAX * 2;
reg = (struct vara*)realloc(reg, new_size * sizeof(struct vara)); //Even if i comment these lines the code works :O
}
split = strtok(line, " "); //Split the line on space delimiter i.e {"1", "apple", "10"}
args[0] = split;
int i = 1;
while (split != NULL)
{
split = strtok(NULL, " ");
args[i] = split;
i++;
}
if (i != 3) //Checking if the args size is three
{
//Copy from args to struct
reg[x].id = atoi(args[0]); //Copy Number
strcpy(reg[x].name, args[1]); //Copy Name
reg[x].price = atoi(args[2]); //Copy Balance
x++;
}
}
(*size) = x;
printf("\nReading Completed!");
fclose(fP);
}
return reg;
}
主要功能:
void main()
{
char fileName[100];
FILE* fP = NULL;
printf("Enter file Name : ");
scanf("%s", fileName);
myprog* reg = malloc(MAX * sizeof * reg); //#define MAX 1
int size = 0;
reg = readFromFile(fP, fileName, reg, &size);
//Some Code below
}
我面临的问题:当我使用定义为 1 的 MAX 运行代码时,它会从文件中读取任意数量的产品,而不会出现任何内存泄漏错误。它甚至可以在没有 realloc 的情况下工作,你能帮我找出我的错误吗? 输入文件中的数据如下所示:
1 prod_a 15
2 prod_b 20
答: 暂无答案
评论
MAX
int new_size
if(x >= new_size) { new_size += MAX; /*etc*/}
sizeof * reg
sizeof(*reg)
sizeof(reg)