c - 同样的C程序在Windows上无法运行,但在Linux上却可以完美运行

标签 c

我编写了一个非常基本的程序来从文件中读取非常大的数字并计算连续数字的最大乘积。为了提醒一些 C 基础知识,我决定用 C 语言编写它。在我装有 Linux 的家用机器上,它运行得非常顺利。在 Visual Studio 2013 Express 上,它会抛出一些错误并挂起(可能与内存管理有关)。你知道发生了什么事吗?

int ch, i = 0, *ptr, count = 0, j;
FILE *f;
int *arr;

//Opening file in read mode
f = fopen("test.txt", "r");
if (f == NULL) {
    printf("Error");
    return 0;
}

//intial allocation
arr = malloc((count + 1) * sizeof(int));
ptr = arr;

while ((ch = fgetc(f)) != EOF) {
    if (ch == 10) {
        continue; //exclude new line character
    }
    *ptr = (ch - 48); //populating array

    ptr++;
    count++;
    arr = realloc(arr, (count + 1) * sizeof(int));
}

int p0 = 1;
int maxp = 1;

//calculating largest product of five consecutive digits 
for (i = 0; i < count - 5; i++) {
    p0 = 1;
    for (j = 0; j < 5; j++) {
        p0 *= arr[i + j];
    }
    if (maxp < p0) {
        maxp = p0;
    }
}

printf("%d", maxp);

return EXIT_SUCCESS;

最佳答案

在 while 循环中,您每次都会重新分配缓冲区(顺便说一句,这是完全低效的,但那是另一个故事了)。但是您继续使用 ptr 指针,该指针指向在 while 循环之前由 malloc 分配的缓冲区。 realloc 函数可能返回与先前分配的指针的地址相同的地址,在这种情况下您的程序似乎可以工作。但是,如果返回的地址不同,则ptr不再有效,您的程序将无法运行,甚至可能崩溃。

这应该可行(尽管效率仍然很低):

while ((ch = fgetc(f)) != EOF) {
    if (ch == 10) {
        continue; //exclude new line character
    }

    arr[count++] = (ch - 48); //populating array
    arr = realloc(arr, (count + 1) * sizeof(int));
}

关于c - 同样的C程序在Windows上无法运行,但在Linux上却可以完美运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22499042/

相关文章:

c - 链表令人困惑

c - ipc - shm - 字符串会保留在内存中直到系统重新启动吗?

C 在 for 循环中没有 printf

c - 在 C 中打印数组时出错

c - 为什么我不能声明和定义一个字符指针变量来指向一个字符数组?

C 重复数组

c - 十六进制枚举或整数(ASCII)枚举来填充字节数组?

c - 通过引用传递字符串变量

c++ - 拼接全景图像

C Matrix redimensioning导致段错误