stack smashing detected by valgrind

a stack smashing is detected in my main function in a c++ code... here is the body of 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 accountn2. Transactionn3. ExitnnEnter 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);
}

When i run the code through valgrind it also finds the stack smashing but can't find any memory leak. valgrind report:

1.New account 2. Transaction 3. Exit

Enter choice:3 * stack smashing detected * : ./a.out terminated Thank you==9813==

==9813== HEAP SUMMARY:

==9813== in use at exit: 0 bytes in 0 blocks

==9813== total heap usage: 10 allocs, 10 frees, 954 bytes allocated

==9813==

==9813== All heap blocks were freed -- no leaks are possible

==9813==

==9813== For counts of detected and suppressed errors, rerun with: -v

==9813== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0) Aborted (core dumped)

Where am i going wrong?


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 1993n" , 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.

链接地址: http://www.djcxy.com/p/64946.html

上一篇: 找出valgrind提出的问题

下一篇: 由valgrind检测到堆栈粉碎