Reputation: 925
I'm trying to implement the program, which recognizes Windows file attributes. I have a code, but sometimes, I receive heap error after passing return in the main block. Thank you for your attention and help!
#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;
}
Upvotes: 0
Views: 79
Reputation: 8313
you input whole string into 1 or 2 bytes strings. These allocations:
_TCHAR* attString = new _TCHAR();
char* ynAnswer = new char();
Allocate only 1 item array.
it should be:
_TCHAR* attString = new _TCHAR[MAX_SIZE];
char* ynAnswer = new char[MAX_SIZE];
When MAX_SIZE
must beeb defuned as macro.
even better is to use:
wstring attString ;
string ynAnswer;
wcin>> attString;
cin>> ynAnswer;
More problem is the allocation in the line:
argv[1] = new _TCHAR();
in addition to the previous answered problem, in this line argv[1]
may not even exists.
You should input to other buffer.
it can be like this:
wstring argv1;
if(argc <2){
wcin>>argv1;
}else{
argv1=argv[1];
}
now use argv1
instead of argv[1]
One more thing:
You are using _TCHAR
as WCHAR
.
when you use _TCHAR
strings should be decalared as:
_T("some string")
not as:
L"some string"
.
Upvotes: 1