Problem with LPBYTE lpBuffer - I always get the variable error - <bad ptr>

Hello all!

I've got a problem with the variable LPBYTE lpBuffer - Debug watch
reports me that this variable has a bad ptr. Then it's the cause that
I'm not able to get success with loading my file which I need to see in
my dialog's edit-box.

This is the problem part of my code:
__________________________________________________________________________
	HANDLE hFile;
	DWORD dwSize;
	DWORD dw;
	LPBYTE lpBuffer = NULL;
	lstrcpy(szSoubor, TEXT("\\temp\\test.txt"));
	hFile  = CreateFile(szSoubor, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0,
NULL);
	if(hFile == INVALID_HANDLE_VALUE)
		return;
	dwSize = GetFileSize(hFile, NULL);
	lpBuffer = (LPBYTE)HeapAlloc(GetProcessHeap(),
HEAP_GENERATE_EXCEPTIONS, dwSize+1);
	if(!ReadFile(hFile, lpBuffer, dwSize, &dw, NULL)){
		CloseHandle(hFile);
		HeapFree(GetProcessHeap(), 0, lpBuffer);
		return;
	}
	CloseHandle(hFile);
	lpBuffer[dwSize] = 0;
	SetDlgItemText(hwndDlg, IDC_EDIT1, (LPCTSTR)lpBuffer);
	SetFocus(hwndDlg);
	return;
___________________________________________________________

Did I do something wrong or did I forget something?
(I need the command <if(!ReadFile(...))> to get nonzero result.)

Thank you very much for any help!

0
miuss (3)
8/28/2006 12:35:25 PM
vc.mfc 33608 articles. 0 followers. Follow

3 Replies
586 Views

Similar Articles

[PageSpeed] 45

Did you step through the code to make sure that the file opens, and that
GetFileSize returns a none zero value, and that HeapAlloc is actually
allocating your buffer?

AliR.

<miuss@seznam.cz> wrote in message
news:1156768524.907270.187820@i42g2000cwa.googlegroups.com...
> Hello all!
>
> I've got a problem with the variable LPBYTE lpBuffer - Debug watch
> reports me that this variable has a bad ptr. Then it's the cause that
> I'm not able to get success with loading my file which I need to see in
> my dialog's edit-box.
>
> This is the problem part of my code:
> __________________________________________________________________________
> HANDLE hFile;
> DWORD dwSize;
> DWORD dw;
> LPBYTE lpBuffer = NULL;
> lstrcpy(szSoubor, TEXT("\\temp\\test.txt"));
> hFile  = CreateFile(szSoubor, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0,
> NULL);
> if(hFile == INVALID_HANDLE_VALUE)
> return;
> dwSize = GetFileSize(hFile, NULL);
> lpBuffer = (LPBYTE)HeapAlloc(GetProcessHeap(),
> HEAP_GENERATE_EXCEPTIONS, dwSize+1);
> if(!ReadFile(hFile, lpBuffer, dwSize, &dw, NULL)){
> CloseHandle(hFile);
> HeapFree(GetProcessHeap(), 0, lpBuffer);
> return;
> }
> CloseHandle(hFile);
> lpBuffer[dwSize] = 0;
> SetDlgItemText(hwndDlg, IDC_EDIT1, (LPCTSTR)lpBuffer);
> SetFocus(hwndDlg);
> return;
> ___________________________________________________________
>
> Did I do something wrong or did I forget something?
> (I need the command <if(!ReadFile(...))> to get nonzero result.)
>
> Thank you very much for any help!
>


0
AliR3470 (3236)
8/28/2006 3:29:18 PM
If you are using MFC, then use this(UNTESTED):-
CByteArray Buffer;
DWORD dwSize = GetFileSize(hFile, NULL);
Buffer.SetSize(dwSize);
LPBYTE pBuffer = Buffer.GetData();
ReadFile(hFile, pBuffer, dwSize, &dw, NULL);

By doing so, you don't have to worry about memory leaks and so on.
-- 
Vipin Aravind
http://www.explorewindows.com/Blogs


<miuss@seznam.cz> wrote in message 
news:1156768524.907270.187820@i42g2000cwa.googlegroups.com...
> Hello all!
>
> I've got a problem with the variable LPBYTE lpBuffer - Debug watch
> reports me that this variable has a bad ptr. Then it's the cause that
> I'm not able to get success with loading my file which I need to see in
> my dialog's edit-box.
>
> This is the problem part of my code:
> __________________________________________________________________________
> HANDLE hFile;
> DWORD dwSize;
> DWORD dw;
> LPBYTE lpBuffer = NULL;
> lstrcpy(szSoubor, TEXT("\\temp\\test.txt"));
> hFile  = CreateFile(szSoubor, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0,
> NULL);
> if(hFile == INVALID_HANDLE_VALUE)
> return;
> dwSize = GetFileSize(hFile, NULL);
> lpBuffer = (LPBYTE)HeapAlloc(GetProcessHeap(),
> HEAP_GENERATE_EXCEPTIONS, dwSize+1);
> if(!ReadFile(hFile, lpBuffer, dwSize, &dw, NULL)){
> CloseHandle(hFile);
> HeapFree(GetProcessHeap(), 0, lpBuffer);
> return;
> }
> CloseHandle(hFile);
> lpBuffer[dwSize] = 0;
> SetDlgItemText(hwndDlg, IDC_EDIT1, (LPCTSTR)lpBuffer);
> SetFocus(hwndDlg);
> return;
> ___________________________________________________________
>
> Did I do something wrong or did I forget something?
> (I need the command <if(!ReadFile(...))> to get nonzero result.)
>
> Thank you very much for any help!
> 


0
vipin (696)
8/28/2006 6:44:55 PM
See below...

On 28 Aug 2006 05:35:25 -0700, miuss@seznam.cz wrote:

>Hello all!
>
>I've got a problem with the variable LPBYTE lpBuffer - Debug watch
>reports me that this variable has a bad ptr. Then it's the cause that
>I'm not able to get success with loading my file which I need to see in
>my dialog's edit-box.
>
>This is the problem part of my code:
>__________________________________________________________________________
>	HANDLE hFile;
>	DWORD dwSize;
>	DWORD dw;
>	LPBYTE lpBuffer = NULL;
>	lstrcpy(szSoubor, TEXT("\\temp\\test.txt"));
****
Why use lstrcpy?  Why not just do
	LPCTSTR szSoubor = _T("....");
or
	CString Soubor(_T("..."));
?
*****
>	hFile  = CreateFile(szSoubor, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0,
>NULL);
*****
	CFile f;
	
	BOOL ok = f.Open(Soubor, CFile::modeRead);
****
>	if(hFile == INVALID_HANDLE_VALUE)
>		return;
****
	if(!ok)
	   {
                    ... report error
                    return FALSE;
                   }
>	dwSize = GetFileSize(hFile, NULL);
****
Do not presume that dwSize should be a DWORD, and in fact don't even use that horrible
Hungarian Notation that presumes you know what the variable size might be!  Note how badly
the use of Hungarian Notation collapses when you move to a 64-bit world.
	ULONGLONG Size = f.GetLength();
If you are running on Win2K or later, and you insist on using the API instead of CFile, do
	ULONGLONG Size;
                if(!GetFileSizeEx(hFile, &Size);
which at least has the charm of actually working, particularly for large files on Win64.
****
>	lpBuffer = (LPBYTE)HeapAlloc(GetProcessHeap(),
>HEAP_GENERATE_EXCEPTIONS, dwSize+1);
****
This seems overly complex.  
	lpBuffer = new BYTE[dwSize + 1];
I note that you actually have nothing that handles C structured exceptions, which should
not be mixed with C++.  So using HeapAlloc with HEAP_GENERATE_EXCEPTIONS is almost
certainly a bad idea.  Avoid HeapAlloc in general.  There are very few places where it
makes sense to call it directly.  This is not one of them.
****
>	if(!ReadFile(hFile, lpBuffer, dwSize, &dw, NULL)){
>		CloseHandle(hFile);
>		HeapFree(GetProcessHeap(), 0, lpBuffer);
****
		delete [] lpBuffer;
****
>		return;
>	}
>	CloseHandle(hFile);
>	lpBuffer[dwSize] = 0;
>	SetDlgItemText(hwndDlg, IDC_EDIT1, (LPCTSTR)lpBuffer);
****
Avoid SetDlgItemText.  Rename the control to have some meaningful name, not IDC_EDIT1, and
then use the Class Wizard to bind it to a variable, and do
	c_WhateverYouCalledTheVariable.SetWindowText((LPCTSTR)lpBuffer);
However, this presumes that the file, if read by a Unicode app, is in Unicode.  This is
not a safe assumption, so for proper Unicode compatibility you would have to make sure
that you handle the Unicode/ANSI conversions properly.
****
>	SetFocus(hwndDlg);
****
There is no reason to do this.  The dialog already has the focus.  If you wanted to set
the focus to the edit control, you would write
	c_WhateverYouCalledTheVariable.SetFocus();
and, if this is in OnInitDialog, make sure you return FALSE from OnInitDialog.
****
>	return;
>___________________________________________________________
>
>Did I do something wrong or did I forget something?
>(I need the command <if(!ReadFile(...))> to get nonzero result.)
>
>Thank you very much for any help!
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15975)
8/29/2006 1:58:26 AM
Reply:

Similar Artilces:

ExMerge 'Error configuring message service'
Hi All, I am running into this error when trying to import a PST into Exchange 2003 SP1 (on SBS 2003): Error configuring message service (MSPST MS) (MAPI_E_EXTENDED_ERROR) (CMapiSession::CreateEMSPSTProfile) I know this matches a KB article exactly, but the PST is NOT read only (I have even made it read only and then not read only just to make sure). I am pretty sure I have correctly removed deny send and receive as. I can export to a PST from the mailbox in question and then re-import the exported PST. The mailbox does not have any limits and does have messages so it is initialize...

Need help getting files from Exchange Server.
We have a computer that had an account on Outlook attached to a Microsoft exchange server. Apparently for the moment, this computer and the server are inextricably tied together. Outlook cannot even be started without logging into the server because information store or whatever is missing. How do you get the information out of the exchange server to wean the computer from it? tom <Spamblocker@ameritech.net> wrote: > We have a computer that had an account on Outlook > attached to a Microsoft exchange server. > > Apparently for the moment, this computer and the > se...

stack fault error when browsing address book
I have a problem that occurs when browsing the address book "Contacts" that results in the error message: OUTLOOK has caused a stack fault in MSPST32.DLL and the termination of Outlook I've updated the Win98Se and the Office 2000, tried the steps in the KB218853, and searched the newsgroup and KB to no avail. Also tried the Inbox repair tool (scanpst.exe) which found only minor problems and repaired them. I can look at the entire "Contacts" folder in Outlook without problems. This does not appear to be related to any contact record. Thanks Steve ...

How to get TASK_ID field for summary tasks without using Project.a
I know for tasks which are not summary tasks we can get TASK_ID field using statusing web service. But i could nto find any other options than Project web service to get TASK_ID field for summary tasks and the top level project task. Problem of using Project web service is that in my custom sharedpoint web part where we are using PSI web services we get all the data required using Resource and Statusing web service for the logged in resource. But Statusing web service retrieves TASK_ID only for actual tasks and not for summary tasks. Now just to get TASK_ID of summary tas...

minimalist wants to know: is it possible to get a single bar on IE
on IE6 I had my menus, commands, & address window all on the same bar. Why can't I do that with IE8? why is there a 'favorites' button next to my tabs (even with fav bar disabled) when i have a drop-down favorites list from the menu bar anyway? ...& why do I need a search window when my home page is a search engine? too much redundant crap that I cant turn off. I want to get rid of the favorites button, the search box, & put the rest on a single bar... I'd go back to IE6, but Vista wont allow me to view or remove installed MS prgs like XP did. ...

Can't get the proper display of a field in my report.
I have 2 tables, both using autonumbers for their primary key. The first table is for contacts (i.e. last name, first name, etc.). The second table is for businesses (business name, etc.) I have a field in my contacts table that has a number format so it can be used as a foreign key for the business table. I then set up the relationship between them & enforced referential integrity. When I run a query, I see the name of the business (after setting up a combo box) - no problem. When I run a report based on that query, a number is displayed (not the business name). Suggestions, pleas...

Case select returning error when cell contains #N/A : how must i avoid this error
Title says it all Thanks, Luc maybe this will do what you want Sub test() If Not IsError(Range("C1").Value) Then Select Case Range("C1").Value Case 1 MsgBox "1" Case 2 MsgBox "2" End Select End If End Sub -- Gary Keramidas Excel 2003 "Luc" <lferr@live.be> wrote in message news:7AB07996-F1EE-41C1-8D9D-8A7DA54CED91@microsoft.com... > Title says it all > > Thanks, > > Luc Thanks for your help !!!!! Luc "Gary Keramidas" <GKeramidasAtMSN.com> schreef in berich...

Error Code: 0x8024D007
Hi all: I have tried pretty much evrything listed here in other discussions. It appears that my last update was January 2010. I am running XP sp3. I would hope by now Microsoft would have a general fix for WUS issues. I know this is a compllex issue but so many people can no longer get updtaes. is this their way of trying to force us all to Win 7? Any help would be appreciated. Thx Michael Michael, The most common cause of error 0x8024D007 is that registry files that correspond to the Wups2.dll file are missing. However, the problem can also be caused by other mis...

power point error
get the following error when double clicking a slideshow in Outlook: Procedure entry point GetProcessImageFileNameW could not be located in the dynamic link library. PSAPI.DLL Originally I thought it could be a problem with PowerPoint 2007 so I had Unistalled the Office suite and reinstalled it however the problem still arised. Even repairing the Office suite did not help. I tried using the sfc /scannow but to no avale. I also tried renaming the PSAPI.DLL to PSAPIOLD.DLL rebooted the machine and then it created a new PSAPI.DLL file. Still the error arises. Then I had tried repar...

mail sending problem
Hi , I am very new in the exchange server just now I have deployed Microsoft Exchange Server 2003 at my organization now i have some problem in that . I am able to send mail outside the domain except yahoo .whenever I am sending mail from my exchange mail id to any yahoo mail id it is showing me mail has been sent but on yahoo id it is not delivering even I am not getting the DFR, second I wants to know that can we take the backup of single mail box (boxs) and please tell me step by step how can we take backup (at least the location ) Thanks in Advance Madi The most probable reason is t...

Printing in excel always comes out in bold even tho bold not on
When I print in excel my work always comes out in bold even though the bold is not switched on. Any suggestions?? It could be a printer setting. Does it print in bold from other applications? Regards, Fred "Scarlett50" <Scarlett50@discussions.microsoft.com> wrote in message news:DF3BAEA1-4D22-449E-BB8F-31DD8855AF20@microsoft.com... > When I print in excel my work always comes out in bold even though the > bold > is not switched on. Any suggestions?? No only when I have to type a report in excel - the actual report is ok on other computers! but...

Conversion Errors Table
Hello, I'm new to working with Access, I just converted an Access 97 databas into Access 2002. It tells me there were errors, and to look at th Conversion Errors Table. But nowhere in the message or in the MS Hel is there anything telling me where to find this table. Can someon help? Thanks Patric -- psha ----------------------------------------------------------------------- pshaw's Profile: http://www.officehelp.in/member.php?userid=493 View this thread: http://www.officehelp.in/showthread.php?t=125029 Posted from - http://www.officehelp.i I'd expect to find it in the new...

Error C2440 cannot convert from void
I got this error a few days ago and after much searching and still stuck on the problem. Any help given will be greatly appreciated. Error 1 error C2440: 'static_cast' : cannot convert from 'void (__thiscall CPage1::* )(void)' to 'LRESULT (__thiscall CWnd::* )(WPARAM,LPARAM)' The error occurred in this code: BEGIN_MESSAGE_MAP(CPage1, CPropertyPage) //{{AFX_MSG_MAP(CPage1) ON_WM_DESTROY() ON_WM_TIMER() ON_BN_CLICKED(IDC_BUTTON_PROV_ADD, OnButtonProvAdd) ON_BN_CLICKED(IDC_BUTTON_PROV_EDIT, OnButtonProvEdit) ON_BN_CLICKED(IDC_BU...

Incoming mail server problem
I use supanet for the internet and recently had to clear off a load of viruses and worms from my computer. Computer is clean now. I've run up to date spybot. adaware and cleaned all viruses with Mcaffee internet security as well as running stinger. Sasser, and W32 pate.b were included. Have also completed all windows updates. Everything is working fine now except my email. When I restart the computer my incoming mail server keeps changing from pop.supanet.com to a strange number. 9eg 17.02.01.10 or something similar) It also changes the user name from 3612 to 3612@supanet.com (It adds su...

Outlook Web Access attachment problem
We have a program that will generate a .snp file and then email it to whatever recipient it needs to go to. If they receive the email in Outlook it will allow them to open the file properly with the Snapshot viewer. However, if they go to the same email in OWA and try to save the attachment, it attempts to save it as an .mdb file. Why would OWA ignore the original extension and try to give it a different one? "Joe Giddings" <j_nospam_giddings@thehammocksource.com> wrote in news:jI9gd.11726$ta5.6952@newsread3.news.atl.earthlink.net: > We have a program that will genera...

Problems performing a restore to a SAN drive
We recently move our message stores to SAN. I've tried to perform a restore to a recovery storage group on the SAN and am not able to do it. We use Ultrabac as our backup application, but I've tried NTBackup also and am getting the following errors in the App logs: Information Store (3576) Callback function call ErrESECBRestoreGetDestination ended with error 0xC7FE1F42 Database not found. and Failed to find a database to restore to from the Microsoft Active Directory. Storage Group specified on the backup media is e0d4e0af-f91a-490d-9b40-47e27b9fb714. Database speci...

Windows Welcome Screen Login Looping Problem
Up until now no startup problems whatsoever with my system. Today, I press the start button and it boots fine to the Windows' Welcome Screen. When I click on my account icon (no password ever entered) it tries to login (I see my desktop for about 4-5 seconds) but it comes back to the same Windows' Welcome Screen after about 5-10 seconds. My significant other also has an account icon and when she tries to login from the welcome screen she can't get pass the screen either and gets the same 5-10 seconds looping problem that happens to me. System specs: Dell Deminsio...

Outlook OM : Method Restrict() has problems with parentheses
I'm trying to filter for a specific name using; olItems.Restrict("[From] = John Doe()"); Notice the parentheses in the string. If the string contains parentheses in it, I get the following exception. An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in ioemail.dll Additional information: Condition is not valid. How do I get Restrict to work with parentheses? Answer: olItems.Restrict("[From] = 'John Doe()'"); >-----Original Message----- >I'm trying to filter for a specific name using; >olItems.Res...

POP server always changes to localhost
Hello, My outlook is having a wierd issue. I have three POP3 accounts set up to check email in Outlook. After some point in time, all three will stop functioning because in the E-mail accounts settings dialog my incoming mail server will get changed to localhost, and it fails to log in to box to pull my mail. It appends the POP3 server name to my user name which seems odd. So, to summarize, my Incoming mail server (POP3) field changes from it's usual value (something like mail.server.com) to localhost, and my mail server gets appended to my user name (something like username...

Problems with reading date/time format from SQL server
Helo! I made a pivot table. I get data from external source - SQL server. On of the columns is date/time type. For some reason unknown to me, Exce doesn't read this dates correctly. Instead of dots between months an days it puts little squares .. ?!? I opened the same file on m coworkers comp. and it works just fine. If anyone has already encountered this and knows how to fix it .. plase reply. thnx j -- Message posted from http://www.ExcelForum.com There may be some difficulties getting external data properly into Excel. If not done correctly you cannot use the data in formulae e....

XMLA .NET connection problem
Hi, After install msxml 4.0 and XMLASDK 1.1, i proceed to configure the datasource.xml file, as follow: <DataSource> <DataSourceName>FoodMart 2000</DataSourceName> <DataSourceDescription>Microsoft Analysis Server 2000 on local machine</DataSourceDescription> <URL>http://localhost/xmla/msxisapi.dll</URL> <DataSourceInfo>Provider=MSOLAP.2;Data Source=md001144</DataSourceInfo> <ProviderName>Microsoft XML for Analysis</ProviderName> <ProviderType> <TDP/> <MDP/> <DMP/> </ProviderType>...

How to get the handle of a Help file belonging to other process.
Hi all, In my application,I want to change the Index of a HTMLHELP file which belongs to a dialog running in other exe.In order to do this I need to find whether the Help file is open or not & get the handle of that to use HH_DISPLAY_INDEX .Is there any way to do this?? Note: I dont want to use FindWindow() as it is giving rise to some problems in my application.. Thanks in advance ...

Problems with DATE data type
Hi!!! I've got a little problem with the next macro in Excel. The problem is that I must look for some information in a data bas using as filter a specific day an hour in the year. I get the date and the hour using a form and then the macro calle "Busqueda" receives the value. I've programmed the macro using MSQuery just to see the necessary cod and the problem has appeared when I've tried to include the para called "Dia" in the SQL code. I've tried using " & Dia & " but it doesn't work and I don't know ho to include my param...

Error Msg.
Can anyone decipher this error message: DVZMSGR caused an invalid page fault in module MSVCRT.DLL at 0167:78001296. Registers: EAX=00650078 CS=0167 EIP=78001296 EFLGS=00010202 EBX=0075000c SS=016f ESP=0063f728 EBP=0063f748 ECX=0064fc40 DS=016f ESI=0000003f FS=393f EDX=00650448 ES=016f EDI=0000003f GS=0000 Bytes at CS:EIP: 89 4c 11 fc 8b 75 f0 03 d1 8d 4e 01 89 0a 89 4c Stack dump: 00000000 00000040 780013d0 816d0238 00000050 006503c0 0064fc40 00000001 0063f77c 7800145c 0075000c 00000000 ffffffff 780013d0 bff7b9c5 816d0204 ...

Publisher 2003
I'm attempting to print a calendar and I keep getting the message, "Cannot load the printer driver." I have no idea what that means other than I'm unable to print my calendar. Anyone have any ideas? I get the same message whenever I try to print a card I've created. HELP! -- The computer has been chucked out the picture window and the birds are nesting in it. *sigh* Merrie wrote: > I'm attempting to print a calendar and I keep getting the message, > "Cannot load the printer driver." I have no idea what that means > other than I'm una...