473,405 Members | 2,300 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

In multithreaded ex allocating heap memory

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\Client.c(150): error: expression must be a modifiable lvalue
recvbuf2 = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,sizeof(char_36));

char_36 i have used

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

what could the error.
Sep 10 '07 #1
7 4632
Banfa
9,065 Expert Mod 8TB
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
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 __tmainCRTStartup _CrtIsValidHeapPointer Normal 0

how to debug the program
Sep 10 '07 #3
Banfa
9,065 Expert Mod 8TB
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
i have removed the heapfree command also now the error lies in the
waitformultipleinstance()
there are two threads with the handels access and hThread now how should i give the wait,

waitformultipleinstance(2,hThread,access,TRUE,INFI NITE) is this ok or how to specify two handels.
Sep 10 '07 #5
Banfa
9,065 Expert Mod 8TB
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
i changed the handels to array like hthread[0] and hthread[1] then given an array in the waitformultipleobjects(2,hthread,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 Expert Mod 8TB
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
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...
17
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
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...
20
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...
39
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...
5
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...
10
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
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...
1
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....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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...
0
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...
0
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...
0
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...
0
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,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.