Thanks, Carl
Please see my code as below:
//---------------------------------------
1: CString s;
2: int i_num=2;
3: s.Format("%d",i_num);
4: char *strHead = new char[3];
5: strHead ="XX";
6: strcat(strHead,s.GetBuffer());
7: bytesin= (DWORD)strlen(strHead);
8: WriteFile(hReadFile, strHead,bytesin,&bytesout,NULL);
9: delete strHead;
//------------------------------------
When I execute line 6 and 9, it will turn out an unprocessed exception
like
the following format:
ReadDatFiles.exe in 0x10215657 (msvcr71d.dll) unprocessed exception:
0xC0000005: writing location 0x0043209e access confliction.
Why?
Thanks in advance
Joseph
"Carl Daniel [VC++ MVP]"
Joseph Lu wrote:
Hi, all
I use the following codes to create a char array with only three
elements,
/------------------------
char *strHead = new char[0];
bytesin=(DWORD)strlen(strHead)
/---------------------------
but why the values of bytesin is 24, why the value is not zero?
Could any body tell me why?
Undefined behavior. You've allocated an array of 0 bytes and then
called
a function that searches for the first 0-valued byte in that array -
immediately over-indexing the array and reading whatever garbage lies
beyond the array in memory.
What were you trying to do? If you want an array of 3 characters,
allocate an array of 3 characters. But even then, you can't just apply
strlen to a freshly allocated array - the newly allocated array has
undefined content (although under Windows it will frequently contain
0's).
In order to have a defined result, you need to initialize the contents
of
the array before using a function like strlen on it.
-cd