473,769 Members | 6,286 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Strange Corrupt Pointer - Microsoft Bug??

Hi,

I have written a simple program that does the following:

The main program will spown MAX_THREADS number of threads, each
of which will simply add to a global shared counter for MAX_COUNT
times and notify the main thread it has finished by clearing a
mutex before exiting. The main thread will simply check verify the
final result in the global shared counter, wait for each worker
thread has notify finishing, and exit.

The complete C program is at the end of this message. Anyway,
the problem is not in the logic of this program. It is really an
anomaly I encountered while testing it with different values of
MAX_THREADS.
I found that for some reason, if the MAX_THREADS value is 1 or 2 the
hRunMutex[0] will be corrupted during execution for no apparent
reason. The program will go into an infinite loop in CheckCounter()
function. I can detect this by checking if the return value of
WaitForSingleOb ject() function equals WAIT_FAILED, etc, but that's
another topic. So I was playing with the program and tried to
print out the value of hRunMutex[0] at various points and I found
that if I add on extra global variable definition, the whole problem
goes away! That is if I add "char func[10];".

For MAX_THREADS value 3 and above, the program works well with
or without that line. But for value 1 and 2, it has to have that line.
Otherwise it gets a currupt handle during execution and could not
finish.

I am really curious about the cause of this problem. I'd appreciate
if anyone can shed some light on it for me, because besides blaming
Microsoft, I am completely clueless. :)

And the reason I am blaming Microsoft is I am using Visual Studio
..NET to compile the program. Just create a project with Managed C++
Empty Project, and add this file to project to compile and run it.

Thanks!

Regards,
James

/* counters.c file.*/

/* This program will create MAX_THREADS number of threads. Each of
them
* will increment a shared counter for MAX_COUNT times, sleeping for a
* random number of milliseconds in between each increment. The main
* thread will wait until the shared counter reaches
MAX_THREADS*MAX _COUNT.
* It will then wait for enter key from input before exiting to allow
* examining the output.
*/

#include <windows.h>
#include <stdio.h>
#include <process.h>

#define MAX_THREADS 2
#define MAX_COUNT 3

/* getrandom returns a random number between min and max. */
#define getrandom( min, max ) ((rand() % (int)(((max) + 1) - (min))) +
(min))

int main( void ); /* Thread 1: main */
void CountProc( int * MyID ); /* Threads 2 to MAX_THREADS:
Increment the shared counter */
void CheckCounter( void ); /* Function CheckCounter called
by main() */
void WriteMsg( int iThreadNum, int iMyCount, int iTotalCount ); /*
Display information */

HANDLE hRunMutex[MAX_THREADS]; /* Notification mutex */
int iThreadNum; /* Number of threads started */
HANDLE hCounterMutex; /* Shared counter mutex */
int iSharedCounter; /* Shared counter used by all threads
*/
int ThreadID[MAX_THREADS]; /* Thread ID for diaplay */
int done[MAX_THREADS] = {0}; /* Array for thread status */

char func[10]; // Necessary to make it work for MAX_THREADS = 1
and 2 cases. Microsoft bug?!

int main() /* Thread One */
{
/* Create the mutexes and reset thread count. */
int i;
iSharedCounter = 0;
for(i=0;i< MAX_THREADS;i++ )
{
hRunMutex[i] = CreateMutex( NULL, TRUE, NULL ); /* Set */
}
hCounterMutex = CreateMutex( NULL, FALSE, NULL ); /* Cleared */
iThreadNum = 0;

WriteMsg( 0, 0, iSharedCounter );

/* Create the counting threads. */
while( iThreadNum < MAX_THREADS )
{
iThreadNum++;
ThreadID[iThreadNum] = iThreadNum;
_beginthread( CountProc, 0, &ThreadID[iThreadNum] );
}

/* Wait until the shared counter reaches the limit. */
CheckCounter();
WriteMsg( 0, 0, iSharedCounter );

/* All threads done. Clean up handles. */
for(i=0;i<MAX_T HREADS;i++)
{
/* if(done[i] != 1) */
CloseHandle( hRunMutex[i] );
}
CloseHandle( hCounterMutex);

/* Pause for 10 seconds before exiting */
printf("Press enter to exit...");
getchar();
}

void CheckCounter( void ) /* Check shared counter */
{
int i;

/* Check the share counter limit, sleep in between each check */
while ( iSharedCounter < MAX_COUNT * MAX_THREADS)
{
Sleep(getrandom (0,100));
}

/* Wait for the woker threads to exit first */
while ( iThreadNum > 0 )
{
for(i = 0;i<MAX_THREADS ;i++)
{
if(done[i] == 0 )
{
int ret = WaitForSingleOb ject( hRunMutex[i], 100 );
if(ret == WAIT_OBJECT_0 /*|| ret == WAIT_FAILED*/)
{
iThreadNum--;
done[i]=ret+2;
}
}
}
Sleep(getrandom (0,100));
}
}

void CountProc( int *MyID )
{
int i=0;
do
{
/* Wait for counter to be available, then lock it. */
WaitForSingleOb ject( hCounterMutex, INFINITE );
iSharedCounter+ +;
WriteMsg(*MyID, i, iSharedCounter) ;
ReleaseMutex( hCounterMutex );

i++;
Sleep(getrandom (0, 5));
}
while(i < MAX_COUNT);

ReleaseMutex( hRunMutex[(*MyID)-1] );
}

void WriteMsg( int iThreadNum, int iMyCount, int iTotalCount )
{
printf("Thread ID: %d, Local Count: %d, Shared Count: %d \n",
iThreadNum, iMyCount, iTotalCount );
}

Jul 22 '05 #1
2 1815
"James Niceguy" <or*****@yahoo. com> wrote in
news:11******** **************@ f14g2000cwb.goo glegroups.com:
Hi,

I have written a simple program that does the following:

The main program will spown MAX_THREADS number of threads, each
Off-topic.... Standard C++ says nothing about Threads.
of which will simply add to a global shared counter for MAX_COUNT
times and notify the main thread it has finished by clearing a
mutex before exiting. The main thread will simply check verify the
Off-topic.... Standard C++ says nothing about Mutexes.
final result in the global shared counter, wait for each worker
thread has notify finishing, and exit.

The complete C program is at the end of this message. Anyway,
the problem is not in the logic of this program. It is really an
anomaly I encountered while testing it with different values of
MAX_THREADS.
I found that for some reason, if the MAX_THREADS value is 1 or 2 the
hRunMutex[0] will be corrupted during execution for no apparent
reason. The program will go into an infinite loop in CheckCounter()
function. I can detect this by checking if the return value of
WaitForSingleOb ject() function equals WAIT_FAILED, etc, but that's
another topic. So I was playing with the program and tried to
print out the value of hRunMutex[0] at various points and I found
that if I add on extra global variable definition, the whole problem
goes away! That is if I add "char func[10];".

For MAX_THREADS value 3 and above, the program works well with
or without that line. But for value 1 and 2, it has to have that line.
Otherwise it gets a currupt handle during execution and could not
finish.

I am really curious about the cause of this problem. I'd appreciate
if anyone can shed some light on it for me, because besides blaming
Microsoft, I am completely clueless. :)

And the reason I am blaming Microsoft is I am using Visual Studio
.NET to compile the program. Just create a project with Managed C++
Empty Project, and add this file to project to compile and run it.

Thanks!

Regards,
James

/* counters.c file.*/

/* This program will create MAX_THREADS number of threads. Each of
them
* will increment a shared counter for MAX_COUNT times, sleeping for a
* random number of milliseconds in between each increment. The main
* thread will wait until the shared counter reaches
MAX_THREADS*MAX _COUNT.
* It will then wait for enter key from input before exiting to allow
* examining the output.
*/

#include <windows.h>
#include <stdio.h>
#include <process.h>

#define MAX_THREADS 2
#define MAX_COUNT 3

/* getrandom returns a random number between min and max. */
#define getrandom( min, max ) ((rand() % (int)(((max) + 1) - (min))) +
(min))

int main( void ); /* Thread 1: main */
void CountProc( int * MyID ); /* Threads 2 to MAX_THREADS:
Increment the shared counter */
void CheckCounter( void ); /* Function CheckCounter called
by main() */
void WriteMsg( int iThreadNum, int iMyCount, int iTotalCount );
/* Display information */

HANDLE hRunMutex[MAX_THREADS]; /* Notification mutex */
int iThreadNum; /* Number of threads started */
HANDLE hCounterMutex; /* Shared counter mutex */
int iSharedCounter; /* Shared counter
used by all threads */
int ThreadID[MAX_THREADS]; /* Thread ID for diaplay */
int done[MAX_THREADS] = {0}; /* Array for thread status */

char func[10]; // Necessary to make it work for MAX_THREADS = 1
and 2 cases. Microsoft bug?!

int main() /* Thread One */
{
/* Create the mutexes and reset thread count. */
int i;
iSharedCounter = 0;
for(i=0;i< MAX_THREADS;i++ )
{
hRunMutex[i] = CreateMutex( NULL, TRUE, NULL ); /* Set */
}
hCounterMutex = CreateMutex( NULL, FALSE, NULL ); /* Cleared */
iThreadNum = 0;

WriteMsg( 0, 0, iSharedCounter );

/* Create the counting threads. */
while( iThreadNum < MAX_THREADS )
{
iThreadNum++;
ThreadID[iThreadNum] = iThreadNum;
Undefined behaviour. The second time through this loop, you increment
iThreadNum (making it 2) and then attempted to write into an array beyond
its bounds (ThreadID, only has elements 0 and 1).
_beginthread( CountProc, 0, &ThreadID[iThreadNum] );
}

/* Wait until the shared counter reaches the limit. */
CheckCounter();
WriteMsg( 0, 0, iSharedCounter );

/* All threads done. Clean up handles. */
for(i=0;i<MAX_T HREADS;i++)
{
/* if(done[i] != 1) */
CloseHandle( hRunMutex[i] );
}
CloseHandle( hCounterMutex);

/* Pause for 10 seconds before exiting */
printf("Press enter to exit...");
getchar();
}

void CheckCounter( void ) /* Check shared counter */
{
int i;

/* Check the share counter limit, sleep in between each check */
while ( iSharedCounter < MAX_COUNT * MAX_THREADS)
{
Sleep(getrandom (0,100));
}

/* Wait for the woker threads to exit first */
while ( iThreadNum > 0 )
{
for(i = 0;i<MAX_THREADS ;i++)
{
if(done[i] == 0 )
{
int ret = WaitForSingleOb ject( hRunMutex[i], 100 );
if(ret == WAIT_OBJECT_0 /*|| ret == WAIT_FAILED*/)
{
iThreadNum--;
done[i]=ret+2;
}
}
}
Sleep(getrandom (0,100));
}
}

void CountProc( int *MyID )
{
int i=0;
do
{
/* Wait for counter to be available, then lock it. */
WaitForSingleOb ject( hCounterMutex, INFINITE );
iSharedCounter+ +;
WriteMsg(*MyID, i, iSharedCounter) ;
ReleaseMutex( hCounterMutex );

i++;
Sleep(getrandom (0, 5));
}
while(i < MAX_COUNT);

ReleaseMutex( hRunMutex[(*MyID)-1] );
}

void WriteMsg( int iThreadNum, int iMyCount, int iTotalCount )
{
printf("Thread ID: %d, Local Count: %d, Shared Count: %d \n",
iThreadNum, iMyCount, iTotalCount );
}


Jul 22 '05 #2
Hi Andre,

Thank you for the answer! You are right on!! I changed the line to:

ThreadID[iThreadNum-1] = iThreadNum;

and the program works like a charm. Sorry if the policy is not to
discuss off-topic issues here. I will read the rules next time. Guess
I shouldn't be blaming MS so readily!

Regards,
James
Andre Kostur wrote:
"James Niceguy" <or*****@yahoo. com> wrote in
news:11******** **************@ f14g2000cwb.goo glegroups.com:
Hi,

I have written a simple program that does the following:

The main program will spown MAX_THREADS number of threads, each
Off-topic.... Standard C++ says nothing about Threads.
of which will simply add to a global shared counter for MAX_COUNT
times and notify the main thread it has finished by clearing a
mutex before exiting. The main thread will simply check verify the


Off-topic.... Standard C++ says nothing about Mutexes.
final result in the global shared counter, wait for each worker
thread has notify finishing, and exit.

The complete C program is at the end of this message. Anyway,
the problem is not in the logic of this program. It is really an
anomaly I encountered while testing it with different values of
MAX_THREADS.
I found that for some reason, if the MAX_THREADS value is 1 or 2 the hRunMutex[0] will be corrupted during execution for no apparent
reason. The program will go into an infinite loop in CheckCounter()
function. I can detect this by checking if the return value of
WaitForSingleOb ject() function equals WAIT_FAILED, etc, but that's
another topic. So I was playing with the program and tried to
print out the value of hRunMutex[0] at various points and I found
that if I add on extra global variable definition, the whole problem goes away! That is if I add "char func[10];".

For MAX_THREADS value 3 and above, the program works well with
or without that line. But for value 1 and 2, it has to have that line. Otherwise it gets a currupt handle during execution and could not
finish.

I am really curious about the cause of this problem. I'd appreciate
if anyone can shed some light on it for me, because besides blaming
Microsoft, I am completely clueless. :)

And the reason I am blaming Microsoft is I am using Visual Studio
.NET to compile the program. Just create a project with Managed C++
Empty Project, and add this file to project to compile and run it.

Thanks!

Regards,
James

/* counters.c file.*/

/* This program will create MAX_THREADS number of threads. Each of
them
* will increment a shared counter for MAX_COUNT times, sleeping for a * random number of milliseconds in between each increment. The main * thread will wait until the shared counter reaches
MAX_THREADS*MAX _COUNT.
* It will then wait for enter key from input before exiting to allow * examining the output.
*/

#include <windows.h>
#include <stdio.h>
#include <process.h>

#define MAX_THREADS 2
#define MAX_COUNT 3

/* getrandom returns a random number between min and max. */
#define getrandom( min, max ) ((rand() % (int)(((max) + 1) - (min))) + (min))

int main( void ); /* Thread 1: main */
void CountProc( int * MyID ); /* Threads 2 to MAX_THREADS:
Increment the shared counter */
void CheckCounter( void ); /* Function CheckCounter called by main() */
void WriteMsg( int iThreadNum, int iMyCount, int iTotalCount ); /* Display information */

HANDLE hRunMutex[MAX_THREADS]; /* Notification mutex */
int iThreadNum; /* Number of threads started */ HANDLE hCounterMutex; /* Shared counter mutex */
int iSharedCounter; /* Shared counter
used by all threads */
int ThreadID[MAX_THREADS]; /* Thread ID for diaplay */
int done[MAX_THREADS] = {0}; /* Array for thread status */
char func[10]; // Necessary to make it work for MAX_THREADS = 1 and 2 cases. Microsoft bug?!

int main() /* Thread One */
{
/* Create the mutexes and reset thread count. */
int i;
iSharedCounter = 0;
for(i=0;i< MAX_THREADS;i++ )
{
hRunMutex[i] = CreateMutex( NULL, TRUE, NULL ); /* Set */
}
hCounterMutex = CreateMutex( NULL, FALSE, NULL ); /* Cleared */
iThreadNum = 0;

WriteMsg( 0, 0, iSharedCounter );

/* Create the counting threads. */
while( iThreadNum < MAX_THREADS )
{
iThreadNum++;
ThreadID[iThreadNum] = iThreadNum;


Undefined behaviour. The second time through this loop, you

increment iThreadNum (making it 2) and then attempted to write into an array beyond its bounds (ThreadID, only has elements 0 and 1).
_beginthread( CountProc, 0, &ThreadID[iThreadNum] );
}

/* Wait until the shared counter reaches the limit. */
CheckCounter();
WriteMsg( 0, 0, iSharedCounter );

/* All threads done. Clean up handles. */
for(i=0;i<MAX_T HREADS;i++)
{
/* if(done[i] != 1) */
CloseHandle( hRunMutex[i] );
}
CloseHandle( hCounterMutex);

/* Pause for 10 seconds before exiting */
printf("Press enter to exit...");
getchar();
}

void CheckCounter( void ) /* Check shared counter */ {
int i;

/* Check the share counter limit, sleep in between each check */
while ( iSharedCounter < MAX_COUNT * MAX_THREADS)
{
Sleep(getrandom (0,100));
}

/* Wait for the woker threads to exit first */
while ( iThreadNum > 0 )
{
for(i = 0;i<MAX_THREADS ;i++)
{
if(done[i] == 0 )
{
int ret = WaitForSingleOb ject( hRunMutex[i], 100 );
if(ret == WAIT_OBJECT_0 /*|| ret == WAIT_FAILED*/)
{
iThreadNum--;
done[i]=ret+2;
}
}
}
Sleep(getrandom (0,100));
}
}

void CountProc( int *MyID )
{
int i=0;
do
{
/* Wait for counter to be available, then lock it. */
WaitForSingleOb ject( hCounterMutex, INFINITE );
iSharedCounter+ +;
WriteMsg(*MyID, i, iSharedCounter) ;
ReleaseMutex( hCounterMutex );

i++;
Sleep(getrandom (0, 5));
}
while(i < MAX_COUNT);

ReleaseMutex( hRunMutex[(*MyID)-1] );
}

void WriteMsg( int iThreadNum, int iMyCount, int iTotalCount )
{
printf("Thread ID: %d, Local Count: %d, Shared Count: %d \n",
iThreadNum, iMyCount, iTotalCount );
}


Jul 22 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
3202
by: Vinay | last post by:
Hi I have a corrupt word file. I am able to open it with the code given below tr Dim pInfo As System.Diagnostics.ProcessStartInfo = New System.Diagnostics.ProcessStartInfo( pInfo.UseShellExecute = Tru pInfo.FileName = "c:\corrupt.doc Dim p As Process = System.Diagnostics.Process.Start(pInfo Catch ex As Exceptio MsgBox(ex.ToString End Tr
3
6248
by: Jeffrey Baker | last post by:
Hi, I am recompiling a program from VC++ 5.0 to VC++.NET interface. C++ Compliance is tighter. I get the error message before the program finished that stack corrupt around "obj". - this being an object from a statement like obj = new Class; Does anyone have a clue?
4
1909
by: Eric E | last post by:
Hi all, I have a fairly complex form in Access 2000. In particular, it has two subforms on separate tabs of a tab control. For the last two weeks, I've encountered the dreaded : "You can't carry out this action at the present time." error, runtime 2486. Subsequently Access will not exit the form, and shuts down uncleanly. Looking back on the messages here, this seems to be an indication of a corrupt object in the .mdb. So I imported...
2
1748
by: Joseph Macari | last post by:
I recently installed Office2003 on my computer. I had imported (not linked) a couple of tables from an Access 2000mdb into an Access 2003mdb. I had composed various queries and forms with these imported tables...saved the 2003mdb numerous times without incident. I was working on a form with this imported data (not linked) and all of a sudden the data just disapeared (??)....i.e., the data in the two tables was empty!!! No problem;...
1
1949
by: Default | last post by:
Hi, I am new to C#, that is why I am not sure what kind of problem it is: Is VS files corrupted , or something else. that is the problems description: I am working on a small database project. I am not using any data sources Mysql, access etc. Instead I use binary formatter to store and read data. at the beginning the program checks username/password. it does it in the following way: if(form2.initialized) { for(int i=0;...
2
2315
by: Mongoose7 | last post by:
Hi, I am using vc7 to call a dll function from another dll. The function seems to execute correctly (it writes binary data to the registry) but when it comes out of the function, and tries to execute a standard windows debug trace (or any other line of code for that matter, I tried replacing the debug line with) it crashes giving a first chance exception, and then a access violation. I have a feeling that this has something to do with...
2
2353
by: WoodenSWord | last post by:
Hello i would like to share with you my adventure!!! IIS could not load aspx or asmx pages by NO Means! I reinstalled/unistalled/installed IIS .NET FRAMEWORK 1.1 & 2 , Vs2005 ,Sql server 2005 hundreds of times. Searching the forums i found that the most possible solution would be IIS mappings repair by using aspnet_regiis -i. I got the message that aspnet 2 finished installing with no errors. I tried that with every possible...
5
3508
by: Jeff | last post by:
Okay, I'm still new to vb.net 2005 - throught this was a hardware problem, but now I don't know. (I'm having some problem with my newgroup provider, so hopefully this will go through) This problem just started about a week ago, before all was fine. I'm using the code below to access a mysql database. On the line indicated when the connection is opened, the application has been sporatically drawing an error. It doesn't occur very often -...
2
1590
by: danep2 | last post by:
Hello all This is a really strange problem. I have code that performs a few calculations based on input from a joystick, and writes these values to a file using basically the following code: fprintf(fpResults, "i: %4.2f, j: %4.2f", i, j ); This works correctly (literally) 99.9999% of the time. However, once every million or so writes I get the following output:
0
9587
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10211
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10045
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9993
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6672
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3958
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3561
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.