int do_openFile(void)
{
char *p ; /* pointer to outFileName */
char *m ; /* pointer to report date */
char *mon; /* month number in report date */
/* get output file name */
m = pk->CNCRptdate;
m += 2;
strncpy(mon, m, 2);
p = outFileName ;
strcpy(p, pi->CNDExtransit);
p += 5;
strcpy(p, monTab[atoi(mon)]);
p += 3;
strcpy(p, ".");
p += 1;
strcpy(p, "TXT");
/* Open a new file for writing, if file exists, its contents are destroyed
*/
if ((outfile = fopen(outFileName, "w")) == NULL)
{
printf (" \r");
printf ("fopen failed\n");
printf ("Please hit 'PRINT SCREEN' and then hit ENTER to abort...\n");
getch();
return (0);
};
}
Issue: When the control hits the first strncpy() function, it throws "Unhandled exception at 0x00401acd in ICRSEX2B.exe: 0xC0000005: Access violation writing location 0x0040258f."
Pls let me know if any other information is required.
P will have the value of "99999JUL.TXT". But before that there is one more function
strncpy(mon, m, 2), which is causing the problem.
Also pk->CNCRptdate will have "QP0127"
Pls find below the explanation for the code snippet:
/* get output file name */
m = pk->CNCRptdate; m points to start of Report Date (poss format DDMMYY)
m += 2; m moves forward 2 so that it starts at the month (MM)
strncpy(mon, m, 2); month (MM) is copied to mon
p = outFileName ; p points to outFileName
strcpy(p, pi->CNDExtransit); Transit Number is copied to outFileName
p += 5; p moves forward 5
strcpy(p, monTab[atoi(mon)]); three char month from table is copied to outFileName
p += 3; p moves forward 3
strcpy(p, "."); full stop copied to outFileName
p += 1; p moves forward 1
strcpy(p, "TXT"); TXT copied to outFileName
This gives us the output file name format TTTTTMMM.txt, such as 99999JUL.TXT example.
If I understand correctly, the error occurs at strncpy(mon, m, 2);.
That lines attempts to copy 2 chars from 'm' to 'mon'
The declaration of 'mon' is: char *mon; and it is never initialized.
The problem is that you are trying to write at the memory pointed by 'mon' which isn't owned by your program.
You need to allocate that memory if you want to use it. You can declare 'mon' as an array large enough ( keep in mind that C strings are null-terminated ) or keep it as a pointer and allocate it dynamically ( http://www.cplusplus.com/reference/clibrary/cstdlib/malloc/ )