473,804 Members | 2,119 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

In multithreaded ex allocating heap memory

62 New Member
hi,
the error i am getting in main for allocating heap memory for threads is
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include "winsock2.h"
  3. #include <stdlib.h> 
  4.  #include <windows.h>
  5.  #include <strsafe.h>
  6. #define BUF_SIZE 255
  7. #define nofthreads 2
  8.  
  9. typedef struct data
  10. {
  11.     char a[36];
  12. }char_36;
  13. // Initialize Winsock.
  14.     WSADATA wsaData1,wsaData2;
  15.  // Create a socket.
  16.     SOCKET m_socket1,m_socket2;
  17.     SOCKADDR_IN  client1Service,client2Service;
  18.     BOOL wiatall =  TRUE;
  19.     CRITICAL_SECTION cs;
  20.  
  21.  // Send and receive data.
  22.     //int bytesSent;
  23.     int bytesRecv1,bytesRecv2 = SOCKET_ERROR;
  24.     //char sendbuf[32] = "Client: Sending data.";
  25.     char recvbuf1[36] = "";
  26.     char recvbuf2[36] = "";
  27.  
  28.     DWORD WINAPI workerProc( LPVOID lpParam )
  29.     {
  30.          char recvbuf1[36] = "";
  31.          int status ;
  32.          size_t cchStringSize;
  33.          int iResult;
  34.  
  35.         TCHAR msgBuf[BUF_SIZE];
  36.  
  37.  
  38.  
  39.          iResult = WSAStartup( 0X0202, &wsaData1 );
  40.         if ( iResult != NO_ERROR )
  41.  
  42.     StringCchPrintf(msgBuf, BUF_SIZE, TEXT("error at WSASTARTUP")); 
  43.  
  44.  
  45.  
  46.         m_socket1 = socket( AF_INET, SOCK_STREAM,IPPROTO_TCP);
  47.  
  48.        if ( m_socket1 == INVALID_SOCKET ) 
  49.        {
  50.  
  51.          StringCchPrintf(msgBuf, BUF_SIZE, TEXT("error at socket")); 
  52.  
  53.         WSACleanup();
  54.         return(0);
  55.        }
  56.  
  57.  
  58.       client1Service.sin_family = AF_INET;
  59.       client1Service.sin_addr.s_addr = inet_addr( "192.168.0.239" );
  60.       client1Service.sin_port = htons(27015);
  61.  
  62.      do 
  63.       {
  64.        status = connect( m_socket1, (SOCKADDR *) &client1Service, sizeof(client1Service) );
  65.          StringCchPrintf(msgBuf, BUF_SIZE, TEXT("failed to connect")); 
  66.         WSACleanup();
  67.         return(0);
  68.       }while(status == SOCKET_ERROR);
  69.        StringCchPrintf(msgBuf, BUF_SIZE, TEXT("connected to client 1"));
  70.  
  71.        while( bytesRecv1 == SOCKET_ERROR ) 
  72.        {
  73.  
  74.          bytesRecv1 = recv( m_socket1, recvbuf1, 36, 0 );
  75.          if ( bytesRecv1 == 0 || bytesRecv1 == WSAECONNRESET )
  76.           {
  77.             StringCchPrintf(msgBuf, BUF_SIZE, TEXT("connection closed")); 
  78.             break;
  79.           }
  80.         if (bytesRecv1 < 0)
  81.         return(0);
  82.         StringCchPrintf(msgBuf, BUF_SIZE, TEXT("bytes received")); 
  83.       }
  84.           HeapFree(GetProcessHeap(), 0, recvbuf1);
  85.  
  86.      return(0);
  87.     }
  88.  
  89. DWORD WINAPI ThreadProc( LPVOID lpParam )
  90.     {
  91.         TCHAR msgBuf[BUF_SIZE];
  92.         size_t cchStringSize;
  93.         char recvbuf2[36] = "";
  94.         int iResult = WSAStartup( 0X0202, &wsaData2 );
  95.         if ( iResult != NO_ERROR )
  96.  
  97.     StringCchPrintf(msgBuf, BUF_SIZE, TEXT("error at WSASTARTUP")); 
  98.  
  99.         m_socket2 = socket( AF_INET, SOCK_STREAM,IPPROTO_TCP);
  100.  
  101.        if ( m_socket2 == INVALID_SOCKET ) 
  102.        {
  103.          StringCchPrintf(msgBuf, BUF_SIZE, TEXT("error at socket")); 
  104.         WSACleanup();
  105.         return(0);
  106.        }
  107.  
  108.  
  109.       client2Service.sin_family = AF_INET;
  110.       client2Service.sin_addr.s_addr = inet_addr( "192.168.0.091" );
  111.       client2Service.sin_port = htons(27016);
  112.  
  113.      do 
  114.       {
  115.         connect( m_socket2, (SOCKADDR *) &client2Service, sizeof(client2Service) );
  116.          StringCchPrintf(msgBuf, BUF_SIZE, TEXT("failed to connect")); 
  117.         WSACleanup();
  118.         return(0);
  119.       }while(connect == SOCKET_ERROR);
  120.  
  121.      StringCchPrintf(msgBuf, BUF_SIZE, TEXT("Connected to client 2"));
  122.        while( bytesRecv2 == SOCKET_ERROR ) 
  123.        {
  124.  
  125.          bytesRecv2 = recv( m_socket2, recvbuf2, 36, 0 );
  126.          if ( bytesRecv2 == 0 || bytesRecv2 == WSAECONNRESET )
  127.           {
  128.             StringCchPrintf(msgBuf, BUF_SIZE, TEXT("connection closed")); 
  129.             break;
  130.           }
  131.         if (bytesRecv2 < 0)
  132.         return(0);
  133.         StringCchPrintf(msgBuf, BUF_SIZE, TEXT("bytes received")); 
  134.       }
  135.          HeapFree(GetProcessHeap(), 0, recvbuf2);
  136.  
  137.      return(0);
  138.     }
  139.  
  140.  
  141.  
  142. int  main()
  143. {
  144.     DWORD i=1;
  145.     HANDLE hThread,access;
  146.     DWORD dwThreadId,Idthread;
  147.     int Prio=2;
  148.     recvbuf1  = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,sizeof(char_36));
  149.  
  150.    recvbuf2 = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,sizeof(char_36));
  151.  
  152.  
  153.  
  154.  
  155.     hThread = CreateThread( 
  156.             NULL,              // default security attributes
  157.             0,                 // use default stack size  
  158.             ThreadProc,        // thread function 
  159.             recvbuf1,             // argument to thread function 
  160.             0,                 // use default creation flags 
  161.             NULL);   // returns the thread identifier 
  162.     access = CreateThread( 
  163.             NULL,              // default security attributes
  164.             0,                 // use default stack size  
  165.             workerProc,        // thread function 
  166.             recvbuf2,             // argument to thread function 
  167.             0,                 // use default creation flags 
  168.             NULL);   // returns the thread identifier 
  169.  
  170.  
  171.  
  172. if (hThread == NULL) 
  173.    {
  174.       ExitProcess(1);
  175.    }
  176. if(access == NULL)
  177.  {
  178.     ExitProcess(2);
  179.  }
  180.  WaitForMultipleObjects(1,hThread,TRUE,INFINITE);
  181.  //WaitForSingleObject(hThread,INFINITE);
  182.  CloseHandle(hThread);
  183.  CloseHandle(access);
  184.  
  185.    return(0);
  186. }
  187.  


\..\integration \integration\Cl ient.c(150): error: expression must be a modifiable lvalue
recvbuf2 = HeapAlloc(GetPr ocessHeap(), HEAP_ZERO_MEMOR Y,sizeof(char_3 6));

char_36 i have used

typedef struct data
{
char a[36];
}char_36;

what could the error.
Sep 10 '07 #1
7 4656
Banfa
9,065 Recognized Expert Moderator Expert
The error is in the way you declare your data

Expand|Select|Wrap|Line Numbers
  1.     char recvbuf1[36] = "";
  2.     char recvbuf2[36] = "";
  3.  
  4.     DWORD WINAPI workerProc( LPVOID lpParam )
  5.     {
  6.          char recvbuf1[36] = "";
  7.         ...
  8.     }
  9.  
You have declared recvbuf1 and recvbuf2 as arrays of char, HeapAlloc returns a pointer (void *) and it sould be allocated to a variable with a pointer type not an array identifier.

Then additionally in workerProc (and in ThreadProc) you declare receiveBuf1 again hiding your global definition of it. If you want the data on the heap I would have thought you could declare and allocated it inside workerProc removing the need to global data.
Sep 10 '07 #2
gnanapoongothai
62 New Member
The error is in the way you declare your data

Expand|Select|Wrap|Line Numbers
  1.     char recvbuf1[36] = "";
  2.     char recvbuf2[36] = "";
  3.  
  4.     DWORD WINAPI workerProc( LPVOID lpParam )
  5.     {
  6.          char recvbuf1[36] = "";
  7.         ...
  8.     }
  9.  
You have declared recvbuf1 and recvbuf2 as arrays of char, HeapAlloc returns a pointer (void *) and it sould be allocated to a variable with a pointer type not an array identifier.

Then additionally in workerProc (and in ThreadProc) you declare receiveBuf1 again hiding your global definition of it. If you want the data on the heap I would have thought you could declare and allocated it inside workerProc removing the need to global data.
i have removed the heap allocation entirely and made null in thread create and now there is a access violation error

Unhandled exception at 0x7c809576 in Client.exe: 0xC0000005: Access violation reading location 0x000017f4.

the thread s are being created and again in the main the error is

> 2968 __tmainCRTStart up _CrtIsValidHeap Pointer Normal 0

how to debug the program
Sep 10 '07 #3
Banfa
9,065 Recognized Expert Moderator Expert
Have you also removed the calls to HeapFree?

Run the program in the debugger from your IDE. When it stops view the call stack to locate the point in your program where it has gone wrong.
Sep 10 '07 #4
gnanapoongothai
62 New Member
i have removed the heapfree command also now the error lies in the
waitformultiple instance()
there are two threads with the handels access and hThread now how should i give the wait,

waitformultiple instance(2,hThr ead,access,TRUE ,INFINITE) is this ok or how to specify two handels.
Sep 10 '07 #5
Banfa
9,065 Recognized Expert Moderator Expert
The second parameter is wrong, it needs to be an array of handles to wait on. You are passing a single handle.
Sep 10 '07 #6
gnanapoongothai
62 New Member
i changed the handels to array like hthread[0] and hthread[1] then given an array in the waitformultiple objects(2,hthre ad,TRUE,INFINTE )
then while debuuging threads are created and close handel are also being executed while coming to the return state ment the error is like

Run-Time Check Failure #2 - Stack around the variable 'hThread.12113' was corrupted.

what could have possibly went wrong.
thanx for ur help bafna,
Sep 11 '07 #7
Banfa
9,065 Recognized Expert Moderator Expert
Most likely is that somehow you have written outside the bounds of the array.
Sep 11 '07 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

4
3820
by: Shailesh Humbad | last post by:
If a class has no constructor/destructor, is not part of an inheritance heirarchy, is not a template, and only contains members of integral types, then is it okay to allocate it off the heap? Is this bad style? For example: class myClass { public: int myInt;
17
5054
by: Jonas Rundberg | last post by:
Hi I just started with c++ and I'm a little bit confused where stuff go... Assume we have a class: class test { private: int arr; };
94
4788
by: smnoff | last post by:
I have searched the internet for malloc and dynamic malloc; however, I still don't know or readily see what is general way to allocate memory to char * variable that I want to assign the substring that I found inside of a string. Any ideas?
20
2096
by: Neclepsio | last post by:
Hi everyone. I've made a class Matrix, which contains a pointer to the data and some methods which all return a copy of the matrix modified in some way. The program works quite well for small matrices, but as matrix dimension grows up it crashes in deterministic locations depending on data, machine and OS. In particular, this happens when I test it with 3000x3000 matrices (which take up more than 30MB) under three different machines/OSes....
39
2864
by: cj | last post by:
I have a 2005 TCP/IP server that creates a new thread to handle each incoming TCP/IP request. Once the request has been answered by the thread the TCP/IP socket is disconnected and the sub/thread ends. This program originally written in 2003 and I rewrote it in 2005 earlier this year. I don't know how long this has been going on but we just noticed today that the program was using over a gig of virtual memory. Real memory was quite...
5
24837
by: kumarmdb2 | last post by:
Hi guys, For last few days we are getting out of private memory error. We have a development environment. We tried to figure out the problem but we believe that it might be related to the OS (I am new to Windows so not sure). We are currently bouncing the instance to overcome this error. This generally happen at the end of business day only (So maybe memory might be getting used up?). We have already increased the statement heap & ...
10
1771
by: Chris Saunders | last post by:
Here is the declaration of a struct from WinIoCtl.h: // // Structures for FSCTL_TXFS_READ_BACKUP_INFORMATION // typedef struct _TXFS_READ_BACKUP_INFORMATION_OUT { union { //
13
2001
by: charlie | last post by:
I came up with this idiom for cases where a function needs a variable amount of memory for it's temporary storage so as to avoid constantly mallocing. It makes me feel a little uncomfortable to have unfreeable (but still technically reachable) memory hanging around but it is, I think still a useful thing to do: void fn(int *stuff, int nstuffs) { static int *temp_stuff = NULL; static int ntemp_stuffs = 0;
1
2248
by: amollokhande1 | last post by:
Hi All, We have ASP.Net based content management web application. We are performing lots of XML based operations like setting the innerxml, loading the xml, string replace operations on XML etc. As per my observation during these operations,memory keep on allocating on heap and never release untill Garbage collector gets called by system. I also set all the objects to nothing after its use, but still it is not releasing the memory. Can...
0
9715
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
10352
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
10354
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
10097
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9175
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6867
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
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4313
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
3835
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.