user2178841
user2178841

Reputation: 859

Error Writing to File in Visual Studio

Unhandled exception at 0x102e1cee (msvcr100d.dll) in filename.exe 0xC0000005: Access violation writing location 0x00416858 on.

The debugging points to line:

if (_putc_nolock(ch, f) == EOF)

of code

#else  /* _UNICODE */
    if (_putc_nolock(ch, f) == EOF)
#endif  /* _UNICODE */
        *pnumwritten = -1;
    else
        ++(*pnumwritten);
}

in output.c which I believe is linked in visual studio library. I did not link it.

My code is:

body=""
myFile=CreateFile("Sample.txt",FILE_APPEND_DATA,FILE_SHARE_WRITE,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
BufferNo=sprintf(body,"%.5f %[3].5f %[3].5f %[3].5f %[3].5f %[3].5f %[3].5f %[3].5f \n",a1,a2,a3,a4,a5,a6,a7,a8);
WriteFile(myFile,body,lstrlen(body),0,NULL);
CloseHandle(myFile);

I initially wrote to file with following lines. I had to write the heading.

HANDLE myFile=CreateFile("Sample.txt",GENERIC_WRITE,FILE_SHARE_WRITE,0,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,0);
char* HeadingStr="a1   a2   a3   a4   a5   a6   a7   a8 \n";
WriteFile(myFile,HeadingStr,lstrlen(HeadingStr),0,NULL);
CloseHandle(myFile);

How do I solve this error? Note I have write permission. I ran as administrator, too. Note that I have already defined BufferNo, myFile, outside the use in last code.

UPDATE I removed body="" Now I get

filename.exe triggered a breakpoint.

pointing to the file mentioned in comment below.

**EDIT**

Now, I have problem writing. Error reads

Unhandled exception at 0x7c811384 in stabilo.exe: 0xC0000005: Access violation writing location 0x00000000 on.

and points to line

   WriteFile(myFile,body,lstrlen(body),0,NULL);

Upvotes: 0

Views: 495

Answers (2)

Mats Petersson
Mats Petersson

Reputation: 129314

The variable body in this section is incorrect.

body="";
...
BufferNo=sprintf(body,"%.5f %[3].5f %[3].5f %[3].5f %[3].5f %[3].5f %[3].5f %[3].5f\n",
                      a1,a2,a3,a4,a5,a6,a7,a8);

Presumably it's a char * (alhtough I'm just guessing), which means you are trying to write a bunch of number values to a constant string capable of holding exactly zero characters. Since it's a constant, it's non-writeable.

Change it to char body[1000]; or something similar.

Upvotes: 3

Balog Pal
Balog Pal

Reputation: 17163

Your sprintf overruns the buffer for sure. Even worse: you try to write over a string literal.

Upvotes: 0

Related Questions