• 0

Quick query regarding pointer to struct and heapalloc in C++...


Question

Got a quick C++ question here, tl;dr version is: Got a struct with some objects, creating a new array of objects, using heapalloc (which I thought would be similar to initialising them all manually, I can access/change VarB and VarC but whatever I try to do with VarA causes exception nightmare)

Long version: I've got a struct;

typedef struct ThreadSocketData
{
	list<SOCKET*> VarA;
	unsigned int VarB;
	unsigned int VarC;
} THREADSOCKETDATA, *PTHREADSOCKETDATA;

I'm allocating it as a global and in a function as;

PTHREADSOCKETDATA *pDataArrays;
...
pDataArrays = new PTHREADSOCKETDATA[2];
...
pDataArrays[i] = (PTHREADSOCKETDATA)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(THREADSOCKETDATA));

Then I try to use it like so;

pDataArrays[1]->VarB = 5;
cout << pDataArrays[1]->VarB << endl; //works fine
SOCKET *ASocket = new SOCKET;
*ASocket = 5;
pDataArrays[0]->VarA.push_back(ASocket); //exception crazy

I've tried created it alternatively and like so and it seems to work fine;

pDataArrays = new PTHREADSOCKETDATA[2];
pDataArrays[0] = new THREADSOCKETDATA;
pDataArrays[1] = new THREADSOCKETDATA;
pDataArrays[0]->VarC = 5;
pDataArrays[0]->VarB = 4;
pDataArrays[0]->VarA.begin();
SOCKET *ASocket = new SOCKET;
*ASocket = 18;
pDataArrays[0]->VarA.push_back(ASocket);

So why does the second way work but the first doesn't fully work? Surely using heapalloc would have the same effect as manually allocating it all?

10 answers to this question

Recommended Posts

  • 0

Operator new calls constructors, malloc/HeapAlloc don't. My guess is that in your first example, VarA is uninitialized because its constructor hasn't run, so you cannot use it.

This would all be moot if you were using C++ idioms rather than mixing C idioms in there. In C++ you use new and delete, not malloc, unless you're implementing an allocator or something. Actually, scratch that, in modern C++ you don't even write new and delete, you use smart pointers and containers (see for instance http://fr.slideshare.net/sermp/without-new-and-delete ). In your example if you replace all the C-style arrays with std::vector, and all the raw pointers with smart pointers, every constructor and destructor is guaranteed to run exactly when it should and you shouldn't be leaking anything or accessing uninitialized state.

Also, as a matter of style you don't need to write typedef struct MyType {} MYTYPE in C++, just struct MYTYPE {}, and you'd probably want to avoid SCREAMINGCAPS for all your type names if you don't want your code to look like 9-year olds having an internet argument.

  • 0

This is my first program with threading (not done it before) so I've been modifying the sample MSDN code which had it all in caps, not my idea of naming but good idea, I'll change that.

I don't think I can use smart pointers for this though? The pDataArray {i} is sent by reference to thread {i} although I want to be able to manipulate it from within the main thread therefore I left the heapalloc code as it was provided by MS, so if I remove all the heapalloc/heapfree and just use normal new/delete and pass that in CreateThread() it will work?

  • 0
  On 28/10/2015 at 21:08, Andre S. said:

Do you really need to use the Win32 function CreateThread rather than standard C++ threads

Well the problem is I'm making this program across 3 different types of PCs, my home PC has visual studio 2015 so std::thread is fine, I already use it to get the number of CPUs, another has visual studio 2013 and I'm not sure if it fully has std::thread or only parts of it? And the other has visual studio 2010, which doesn't have any std::thread support at all :(.

Using std::thread I can then pass it smart pointers or references to objects I manually new/delete and access them from the thread and main program? Also is there a std:: replacement for Createevent/Resetevent/Setevent/Waitformultipleobjects?

  • 0

VS2015 Community Edition is free ;)

Yes you can pass any object to an std::thread, look at the documentation. For a ManualResetEvent or AutoResetEvent you could implement that pretty straightforwardly with std::condition_variable and std::mutex, there are examples online.

 

  • 0
  On 28/10/2015 at 21:24, n_K said:

Well the problem is I'm making this program across 3 different types of PCs, my home PC has visual studio 2015 so std::thread is fine, I already use it to get the number of CPUs, another has visual studio 2013 and I'm not sure if it fully has std::thread or only parts of it? And the other has visual studio 2010, which doesn't have any std::thread support at all :(.

Using std::thread I can then pass it smart pointers or references to objects I manually new/delete and access them from the thread and main program? Also is there a std:: replacement for Createevent/Resetevent/Setevent/Waitformultipleobjects?

Like everyone says - VS2015 freebie - no need to be complicated

But you never said what sort of code you are making. If it's anything connected with Device drivers then the std stuff is out the window...

  • 0

I've got VS 2015 community on this pc which is fine - it's my PC. The other two PCs are not mine, they're in an educational establishment, I'm not administrator so I can't just install VS 2015 on them and why I have to put up with using 2010 and 2013 also.

I'll see if I can get a portable mingw working on the other PCs and see what happens if I chuck the code at that instead of using 2010 and 2013!

Nope not drivers, just testing out threads and winsock and the like. I've not looked into drivers, can MS drivers use multiple threads (even if not using std::thread threads)? Can Linux modules use threads (using std::thread)?

Thanks!

  • 0

It's a bad idea to mix allocation techniques like that unless you know what you're doing and it's for a good reason. In particular, STL data structures (such as list) only get initialised properly if you use the built-in new() operator to allocate them.

You might be able to get around it by calling new() on VarA after allocating the structure with malloc().

static const int ARRAY_SIZE = 20
THREADSOCKETDATA* myArray = malloc(ARRAY_SIZE * sizeof(THREADSOCKETDATA));

for (int i = 0; i < ARRAY_SIZE; i++)
    myArray[i].VarA = new list<SOCKET*>;
    
// clean up    
free(myArray);

I wouldn't recommend it though.

For efficiency purposes, I'd also allocate the entire array as a contiguous block of memory, rather than making multiple heap allocations for each individual structure.

  • 0
  On 29/10/2015 at 15:39, n_K said:

I've got VS 2015 community on this pc which is fine - it's my PC. The other two PCs are not mine, they're in an educational establishment, I'm not administrator so I can't just install VS 2015 on them and why I have to put up with using 2010 and 2013 also.

I'll see if I can get a portable mingw working on the other PCs and see what happens if I chuck the code at that instead of using 2010 and 2013!

Nope not drivers, just testing out threads and winsock and the like. I've not looked into drivers, can MS drivers use multiple threads (even if not using std::thread threads)? Can Linux modules use threads (using std::thread)?

Thanks!

Threads are easy to make. After that it can get interesting. There is a reason why just about every GUI system is limited to single-threaded.

If you are doing a real device driver for hardware then you have interrupts in which you need to store whatever you need within 30 millisecs and then Queue up worker threads to do the real processing which are also time limited so you then can have long running threads to process stuff as a background service. You need to be very aware of which variables are atomic and which data structures can get clobbered by your interrupt code, your DPC code, your worker thread etc. The killer is multi-core because it's so fast. It can look like impossible things happen like only 1/2 of a store to memory etc but then it turns out that compiler operation wasn't atomic...

The solution most people use is locks. After you do some device driver stuff, you learn to strike a more delicate balance. So learn what's atomic and every O/S has O/S API calls for safe atomic updates I think.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Windows 10 KB5063159 fixes bug that wouldn't let some Microsoft Surface devices boot by Sayan Sen Microsoft released Windows 10 Patch Tuesday updates for the month last week. The one for Windows 10 under KB5060533 / KB5060531 / KB5061010 / KB5060998 introduced a bug that would not let Surface Hub v1 devices start due to a Secure Boot validation issue. As such, Microsoft had paused the update similar to the compatibility blocks or safeguard holds it applies for major feature updates as well. This bug was uncovered after the update went live, as Microsoft later added it to the list of known issues for that update and it also put up a big notice in bold. It wrote: Earlier today, the company released an out-of-band (OOB) update to address the issue. It has been published under KB5063159 and is only being offered to Surface Hub v1 devices instead of the buggy KB5060533 Patch Tuesday one. In the description of the new OOB update, Microsoft writes: You can find the support article for KB5063159 here on Microsoft's website. It is downloaded and installed automatically but users can also manually download it from the Microsoft Update Catalog website.
    • I thought I saw that one, and yeah, it was awhile ago, too..
    • Jumping unicorns says that I forgot you. I never grunt.
    • Microsoft can't help break Windows Outlook as even opening an email now sends it crashing by Sayan Sen It is no surprise that right now, Microsoft's priority is to move users onto the New Outlook for Windows if they haven't done so already. The company began default-deployment of the new app on fresh Microsoft 365 systems and also made switching between the New app and the classic app easier. At the same time, the company is also trying to improve the new app as it recently added yet another feature that will allow people to use the app without an internet connection, and it also blocked more file types to improve security. Perhaps as a consequence of this relentless pursuit, the classic Outlook app has become quite prone to bugs and issues in recent times as Microsoft may be losing its focus. For example, in April, the downloads for Classic Outlook broke and more recently, this month, the tech giant confirmed that a major Calendar feature upgrade has broken the app in several different ways. Microsoft has provided workarounds for several of the issues so check this article out if you are having problems. And the bugs just keep on coming as Microsoft earlier today confirmed that opening emails or starting a new email will now crash the application, and it affects all channels. The company explains: Opening a mail on an email client is probably the most common and basic functionality a user is expected to do, so it is annoying to see such a bug not getting caught during testing. Again, this perhaps indicates that Microsoft's focus maybe elsewhere at the moment. The company has shared the Windows Event Viewer Log for the crash and the problematic OLMAPI32 DLL file is related to Microsoft Messaging Application Programming Interface (MAPI). The issue reminds us of the similar OLEAUT32 dll issue fix in our recent ReactOS article. The event viewer log notes: Faulting application name: OUTLOOK.EXE, version: 16.0.14334.20090, time stamp: 0x683fe030 Faulting module name: OLMAPI32.DLL, version: 16.0.14334.20090, time stamp: 0x683ff910 Exception code: 0xc0000409 Fault offset: 0x00196e1c Faulting process id: 0x9100 Faulting application start time: 0x01dbdbe04fe54514 Faulting application path: C:\Program Files (x86)\Microsoft Office\root\Office16\OUTLOOK.EXE Faulting module path: C:\Program Files (x86)\Microsoft Office\root\Office16\OLMAPI32.DLL Thankfully, Microsoft has issued a workaround for the problem as it currently investigates the bug by manually creating a FORMS2 folder which should exist at the following address: C:\Users\\AppData\Local\Microsoft\FORMS2. Microsoft explains: You can find the support article for the issue here on Microsoft's official website.
    • I have no issue with a service not being offered free. That's perfectly understandable. I do have issue with seeing ads literally everywhere these days, though, plastered in layers over every website and in every app. Especially with how annoying they tend to be (hell, many ads these days even promote literal scams). That's why people use ad blockers. Let me choose. Offer an ad-free experience for a couple of bucks (but be reasonable, don't get too greedy) or ads for free access. Don't make it ads or nothing.
  • Recent Achievements

    • Week One Done
      korostelev earned a badge
      Week One Done
    • Week One Done
      rozermack875 earned a badge
      Week One Done
    • Week One Done
      oneworldtechnologies earned a badge
      Week One Done
    • Veteran
      matthiew went up a rank
      Veteran
    • Enthusiast
      Motoman26 went up a rank
      Enthusiast
  • Popular Contributors

    1. 1
      +primortal
      687
    2. 2
      ATLien_0
      268
    3. 3
      Michael Scrip
      183
    4. 4
      +FloatingFatMan
      177
    5. 5
      Steven P.
      140
  • Tell a friend

    Love Neowin? Tell a friend!