堆的腐败以及如何在char*foobar中交换2个值[50]

Com*_*erd -4 c++ memory debugging heap pointers

这是我的代码,我不明白为什么我得到运行时检查失败#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;
}
Run Code Online (Sandbox Code Playgroud)

sim*_*onc 6

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

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

tempSign[x-1]=temp;
//        ^^
Run Code Online (Sandbox Code Playgroud)