VS2010中的堆错误

时间:2014-11-18 05:06:07

标签: c++ windows msdn

我正在尝试实现识别Windows文件属性的程序。我有一个代码,但有时,我在主块中传递return后收到堆错误。感谢您的关注和帮助!

#include "stdafx.h"
#include <Windows.h>
#include <conio.h>

_TCHAR* getStringAttributes(int value, _TCHAR* str[])
{
    DWORD d = GetFileAttributes(str[value]);
    _TCHAR* temp;

    switch(d)
    {
        case 2048: temp = L"Compressed\n"; break;
        case 32: temp = L"Archive\n"; break;
        case 16: temp = L"Directory\n"; break;
        case 16384: temp = L"Encrypted\n"; break;
        case 2: temp = L"Hidden\n"; break;
        case 128: temp = L"Normal\n"; break;
        case 1: temp = L"Readonly\n"; break;
        case 4: temp = L"System\n"; break;
        case 256: temp = L"Temporary\n"; break;
        default: temp = L"Error or unsupported attribute\n"; break;
    }

    return temp;
}

int _tmain(int argc, _TCHAR* argv[])
{
    _TCHAR* attString = new _TCHAR();
    char* ynAnswer = new char();

    if(argv[1] == NULL)
    {
        printf("%s\n","You didn't type file path. Try again?[Y/N]");
        gets_s(ynAnswer,10);

        if(*ynAnswer == 'y' || *ynAnswer == 'Y')
        {
            printf("%s\n","Type in a path to the file");
            argv[1] = new _TCHAR();
            _getws(argv[1]);

            if(argv[1] != L"")
            {
                printf("%s","Attribute: ");
                attString = getStringAttributes(1,argv);

                _tprintf(attString);
                printf("%s","for\n");
                _tprintf(argv[1]);
            }
        }
    }
    else
    {
        printf("%s","Attribute: ");
        attString = getStringAttributes(1,argv);
        _tprintf(attString);
    }

    printf("%s","Goodbye");
    getch();

    delete[] ynAnswer;
    delete[] attString;

    return 0;
}

1 个答案:

答案 0 :(得分:1)

将整个字符串输入1或2个字节的字符串。 这些分配:

_TCHAR* attString = new _TCHAR();
char* ynAnswer = new char();

仅分配1个项目数组。

它应该是:

_TCHAR* attString = new _TCHAR[MAX_SIZE];
char* ynAnswer = new char[MAX_SIZE];

必须将MAX_SIZE定义为宏。

更好的是使用:

 wstring attString ;
 string  ynAnswer;

 wcin>> attString;
 cin>>  ynAnswer;

更多问题是行中的分配:

 argv[1] = new _TCHAR();

除了之前的回答问题之外,此行argv[1]可能甚至不存在。 你应该输入其他缓冲区。

它可以是这样的:

wstring argv1;
if(argc <2){
   wcin>>argv1;
}else{
   argv1=argv[1]; 
}

现在使用argv1代替argv[1]

还有一件事:

您使用_TCHAR作为WCHAR

当您使用_TCHAR字符串时,应该将其标记为:

_T("some string")

不是:

L"some string"