【问题标题】:Corruption of the heap and how do i swap 2 values in a char* foobar [50]堆损坏以及如何在 char* foobar [50] 中交换 2 个值
【发布时间】:2013-01-14 10:49:32
【问题描述】:

这是我的代码,我不明白为什么会出现运行时检查失败 #2 - 变量“tempSign”周围的堆栈已损坏。我相信错误是由于尝试在 char* tempSign [MAX] 中交换 2 个值而引起的。有人可以解释为什么我会收到此错误并帮助我解决此问题,谢谢。

void constructSet(ZodiacSign *& z,int size)
{

    /*ZodiacSign is a char *
     This is how z was created from the previous function and 
     passed by reference

     ZodiacSign * z;
     z=new char* [num];

    for (int i=0;i<num;i++)
    {
        z[i]=new char [MAXSTR]; 
    } */

    ZodiacSign tempSign [MAX]={"aquarius","pisces","aries","taurus","gemini","cancer","leo",
                               "vergo","libra","scorpio","sagittarius","capricorn"};


    for (int i=0; i<size;i++)
    {
        int x=12;
        int num=(rand()%x);

        char * ptr=tempSign[num];
        strcpy(z[i],ptr);
        swap(num,x,tempSign);

        x--;
    }
}

void swap(int num,int x,ZodiacSign tempSign [MAX])
{
    ZodiacSign temp;

    temp=tempSign[num];

    tempSign[num]=tempSign[x-1];

    tempSign[x]=temp;
}

【问题讨论】:

  • 请修正缩进,并删除所有多余的空格和注释掉的代码...
  • 使用std::string 会容易得多。
  • 不能使用字符串类
  • 另外,我认为它是virgo,而你正在使用它:)
  • @StuartLC - 我认为这是“你”,而你在它! :)

标签: c++ pointers debugging memory heap-memory


【解决方案1】:

constructSet 中循环的第一次迭代将 x 设置为 12。然后swap 将尝试写入 tempSign[12]。 C 数组是从零开始的,因此tempSign 的有效索引为 [0..11]。写入元素 12 是未定义的行为,但很可能会在为 tempSign 分配的内存末尾之后在堆栈上乱写。

您可以通过更改 swap 中的以下行来解决此问题

tempSign[x-1]=temp;
//        ^^

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 2011-06-10
    • 1970-01-01
    相关资源
    最近更新 更多