0

在我的 C++ 代码中的主函数中检测到堆栈粉碎......这是 main 的主体:

int main()
{
    long int acn;
    char dot[15];
    float open_balance=1;
    char k;
    int total_account=0;
    int c;
    static int ac=10000;
    TRANSACTION trn;
    support sprt;
    do{

        cout<<"\n1.New account\n2. Transaction\n3. Exit\n\nEnter choice:"; 
        cin>>k;
        switch(k) { 
            case '1':

                ac+=1;
                time_t rawtime;
                time(&rawtime);
                strcpy(dot,ctime(&rawtime));
                do{
                    if(open_balance<=0)
                        cout<<"Opening BALANCE can not be less than zero";
                    cout<<"\nEnter the opening balance :";
                    cin>>open_balance;
                }while(open_balance<=0);
                bln[total_account].get_data(ac,open_balance,dot);
                ++total_account;
                break;
            case '2':
                trn.trans(total_account);
                break;
            case '3': break;
            default :
                      cout<<"\nWrong choice!!";
        }
    }while(k!='3');
    cout<<"Thank you";
    return(0);
}

当我通过 valgrind 运行代码时,它也发现堆栈粉碎但找不到任何内存泄漏。valgrind 报告:

1.新账户 2.交易 3.退出

输入选项:3 * 检测到堆栈粉碎 * : ./a.out 已终止 谢谢==9813==

==9813== 堆摘要:

==9813== 退出时使用:0 个块中的 0 个字节

==9813== 总堆使用量:10 分配,10 释放,954 字节分配

==9813==

==9813== 所有堆块都被释放——不可能有泄漏

==9813==

==9813== 对于检测到和抑制的错误计数,重新运行:-v

==9813== 错误摘要:来自 0 个上下文的 0 个错误(抑制:来自 0 的 0 个)中止(核心转储)

我哪里错了?

4

1 回答 1

1

it's the line strcpy(dot,ctime(&rawtime)); which causes the stack smeshing.
function ctime returns a string alike "Wed Jun 30 21:49:08 1993\n", its length is more than 15 bytes, and you need more bytes to store the result of ctime.
strcpy does not check the margin of target memory, so it is considered dangerous, alternative strncpy is suggested instead. And, if your program runs more than one thread, ctime_r is preferred.

于 2014-10-24T08:32:47.700 回答