简体   繁体   English

无法分配堆内存

[英]Trouble allocating heap memory

Background: I am trying to open a file that I altered and reserve enough heap memory for all its' contents. 背景:我正在尝试打开一个已更改的文件,并为其所有内容保留足够的堆内存。 However, I am struggling to find a solution to the program ending before all the file's contents are read into heap memory. 但是,在所有文件的内容读入堆内存之前,我都在努力寻找一种解决方案的解决方案。

Best Guess: I do not think I have reserved enough bytes in heap memory || 最好的猜测:我认为我没有在堆内存中保留足够的字节数。 I have cast my pointer as the wrong type (currently it is type char), which may have adversely affected the way in which and how much of my heap memory was reserved. 我将指针转换为错误的类型(当前为char类型),这可能对保留堆内存的方式和数量产生了不利影响。

FILE *fptr3;

void highgest_and_lowest_Jan123(void)
{
int c;
unsigned int i = 0;
char *file;
long int size = 0;


fptr3 = fopen("/Users/sam/Desktop/Altered_AL_Weather_Station.txt", "r+");
if (fptr3 == 0)
{
    printf("There was an error creating the file.\n");
    exit(0);
}

fseek(fptr3, 0, SEEK_END);
size = ftell(fptr3);
file = (char *) malloc(size * sizeof(char));
if(!file)
{
    puts("Not enough memory");
    exit(1);
}

fseek(fptr3, 0, SEEK_SET);

do
{
    c = fgetc(fptr3);
    if ((int)c == EOF)
        break;
    file[i] = c;
    printf("%c", file[i]);
    i++;
} while((int)c != EOF);

// pus memory back on the heap
free(file);

}

Here is what my current output is: 这是我当前的输出是: 在此处输入图片说明

But, here is what my output SHOULD BE: 但是,这是我的输出应为: 在此处输入图片说明

EOF is expanding to a value of -1 on most systems. 在大多数系统上, EOF都扩展为-1 fgetc is returning int . fgetc返回int But you are reading it into a char variable. 但是您正在将其读入char变量。 Now assume that your file is containing a value of 0xFF . 现在,假设您的文件包含0xFF的值。 In this case the byte value of c would be 0xFF , which, when cast to int will become 0xFFFFFFFF , which is a representation for int -1 value. 在这种情况下, c的字节值将为0xFF ,当转换为int将变为0xFFFFFFFF ,这是int -1值的表示。 Then it is compared to EOF , and the comparison returns true, effectively stopping your loop. 然后将其与EOF进行比较,并且比较返回true,从而有效地停止了循环。 Solution: Declare c as int . 解决方案:将c声明为int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM