【问题标题】:Having Run time check failure #2-stack around the variable "numbers"运行时检查失败 #2-stack 围绕变量“numbers”
【发布时间】:2012-07-05 02:55:27
【问题描述】:

我有如下所示的输入文件

5

8

10

实际上我需要在上面的示例中读取文件更多行。(中间没有空格。因此,我需要让数组的大小取决于文本文件的行。这是我使用的方法通过发生 r

#include "stdafx.h"
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int _tmain(int argc, _TCHAR* argv[])
{
    FILE *test;
    int numbers[]={0};
    int i=0;
    char *array1;
    if((test=fopen("Input1.txt","r"))==NULL)
    {
        printf("File could not be opened\n");
    }
    else
    {
        array1 = (char*)malloc(1000*sizeof (char));
        if((test=fopen("Input1.txt","r"))==NULL)
        {
            printf("File could not be opened\n");
        }
        else
        {
            while(fgets(array1,(sizeof array1)-1,test)!=NULL) 
            {
                numbers[i]=atoi(array1);
                i++;
            }
            for(i=0;i<sizeof(array1)-1;i++)
            {
                printf("%d\n",numbers[i]);
            }
        }
    fclose (test);
    }
    system("pause");
    return 0;
    free(array1);
}

【问题讨论】:

  • 您在numbers 的定义中缺少元素计数(例如numbers[1000])。
  • 但我需要它随文本大小而变化。如果文本大小大于我所拥有的,那么我也会面临错误
  • @user15020809 好的,所以...动态分配它。如果需要,以某个固定长度开始。您以后可以随时使用realloc 对其进行扩展。
  • 如何使用 realloc 来扩展它??在这种情况下?

标签: c error-handling runtime-error


【解决方案1】:

您正在使用sizeof 做一些它不能做的事情。
sizeof array1 是变量array1 的大小。由于它被定义为char *,所以大小就是指针的大小(32 位系统中为 4,64 位系统中为 8)。
您显然想要array1 指向的分配内存量。但是sizeof不能给。

您需要使用分配的大小 - 在您的情况下为 1000。最好将它放在一个变量中,而不是在两个地方使用数字 1000(因为那样,如果您更改一个,您可能会忘记更改另一个)。

【讨论】:

    【解决方案2】:

    例如

    {
        FILE *test;
        int *numbers=NULL;
        int i=0,size=0;
        char array1[1000];//don't need dynamic allocate
    
        if((test=fopen("Input1.txt","r"))==NULL)
        {
            printf("File could not be opened\n");
        }
        else
        {
            while(fgets(array1, sizeof(array1), test)!=NULL) 
            {
                numbers=(int*)realloc(numbers,sizeof(int)*(i+1));
                numbers[i++]=atoi(array1);
            }
            size=i;
            for(i=0;i<size;i++)
            {
                printf("%d\n",numbers[i]);
            }
            fclose(test);
            free(numbers);
        }
        system("pause");
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 2013-12-13
      • 2013-12-10
      • 2015-02-09
      相关资源
      最近更新 更多