PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

Interesting Puzzle

I was debugging a program today which uses the Infrared port and found a crash in X86 Debug mode (in the emu) which I traced to these two lines of code someone wrote:

portName = _T("DUMMY_PORT_NAME");
wsprintf(portName,_T("COM%d:"),portNumber);

Now my few thought was "Ah - that's a bug, portName should be a TCHAR array, not a pointer to some static data".

But then I thought about it further, and thought "Well DUMMY_PORT_NAME is certainly a long enough buffer, why should it crash?". portNumber is 1.

The other weird thing is the exception happens nowhere near any code!

Exception 00e Thread=81d18000 Proc=c1d8afca
AKY=00000801 PC=01fcad53 ESP=1816f3f4 EA=00015464

EAX = 00015464 EBX = 80200043
ECX = 00000043 EDX = 00000000
ESI = 1816F890 EDI = 00000008
EIP = 01FCAD53 ESP = 1816F3F4
EBP = 1816F3FC EFL = 00003217 CS = 0019
DS = 0040 ES = 0040 SS = 0021 FS = 0060
GS = 0000 OV=0 UP=0 EI=1 PL=0 ZR=0 AC=1
PE=1 CY=1


Any ideas? This one's got me puzzled...
ChezDoodles · 27 Jan 2003, 13:01 UTC
It could be that the compiler treats your text string as a constant and put it in a write-protected segment along with the rest of your code.
I can't really do much but confirm ChezD's suspicions. This works (compiled in Visual C++ 6.0 on x86):

Code:
#include<stdio.h>

void main(void) {
char *portName=new char[1000];
char *portName2 = "DUMMY_PORT_NAME";
*portName='f';
}


This, however, doesn't (access violation):

Code:
#include<stdio.h>


void main(void) {
char *portName=new char[1000];
char *portName2 = "DUMMY_PORT_NAME";
*portName2='f';
}


I never knew that Microsoft compilers prevented you from writing to strings defined as literals. Wierd.

And before anybody points it out, yes this is a bad example of c/c++ coding making use of both languages, sorry bout that :D
I never knew that Microsoft compilers prevented you from writing to strings defined as literals. Wierd.


It could be that they're expecting to be able to use the same data-area literal in many places - allowing somebody to write to "one" of the literals breaks the "others".

Anyway, writing to literals is a very dubious practice...
According to MSDN there's a compiler switch that allows you to specify "point identical literals to the same place" but i don't think this is enabled by default.

I'm kinda surprised that the compiler doesn't at least warn about this.