• 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

    • That would have been a so much better UX that what it is right now. I know that after a few moment of trying/failing to recognize you in the dark it goes back to PIN selection. But if the light sensor would detect the dark light, showing the PIN field while continuing for a brief moment to register your face would work better.
    • Oh ! This is why... Like some of you, i used Windows Hello since the Surface Pro 4. It worked really well for so long on many devices and still use it everyday with my desktop and laptop. I couldn't understand why it wasn't working as well as before in the dark. Why is Microsoft (as a company) in its UX decisions so anti-consumer right now ? -_-"
    • Zen Browser 1.13.2b is out.
    • KDE Plasma 6.4 launches, bringing better window management, improved KRunner, and more by David Uzondu It's finally here. After several weeks of development, KDE Plasma 6.4 has been rolled out, delivering a ton of significant refinements across the entire UX, from how you manage windows to how you see notifications. The biggest deal for power users is probably the increased flexibility in window management. Plasma 6.4 now allows you to set a completely different tiling layout for each virtual desktop. You can have a simple 50/50 split screen on one desktop for writing, and on another, have a complex grid with two apps snapped to the sides and two others floating in the middle. On the visual side, the default Breeze Dark theme got a little darker for better contrast, and when a password box pops up, the rest of the screen dims to help you focus. There is also a new Animations page in System Settings, which groups all the purely visual effects in one place so you can find them easily. The file transfer notification now shows a speed graph, giving you a much better idea of how a download is progressing. The system will even pop up a notice if you try talking into a muted microphone, and you can install system updates right from the notification that tells you they are ready. When you are in a full-screen application like a game or watching a movie, Plasma automatically enters a Do Not Disturb mode, holding back notifications until you are done. Plasma 6.3, which was released last February, brought several features, including a "Help" category to the launcher after getting rid of the "Settings" one. Now, Plasma 6.4 gives the application launcher a green New! tag next to recently installed apps to help you find them. KRunner and Spectacle, two of the most powerful utilities in Plasma, also received some serious attention. KRunner now lets you visualize colors just by typing in their hex code or even CSS names like "MintCream" or the ridiculous "PapayaWhip." The tool will then show you what that color looks like and give you its code in other formats. Spectacle, the screenshot tool, has been completely overhauled. Pressing the Print Screen key now immediately puts you in selection mode, letting you grab a region or the whole screen much faster before jumping straight into the annotation tools. Screen recordings made in the WebM format or on screens with fractional scaling have also seen a massive quality boost. The Bluetooth widget is getting smarter with better device recognition and easier pairing (we touched on this last month). People with nice monitors will appreciate the new HDR calibration wizard in the display settings. Plasma can also now handle Extended Dynamic Range and the P010 video format, improving power efficiency with HDR content. Digital artists were not left out either. Configuring the buttons on a stylus is "much more intuitive," and you can easily reset your tablet's calibration if you mess it up. Finally, there is a lot of work under the hood. The System Monitor can now show GPU usage for Intel and AMD hardware on a per-process basis and has a new Sensors page for nerds who want to see raw temperature data. When you drag and drop files on the same disk, you can now set it to always move them instead of asking what to do every time. The browser integration feature now supports the Flatpak versions of Firefox and Chromium-based browsers. All of this is built on top of support for a slew of new Wayland protocols, like "FIFO", "toplevel tag," and more. For more information, you can check out the official announcement post, as well as the full changelog.
    • Zoom Workplace 6.5.0.6118 by Razvan Serea Zoom Workplace for Windows is a reliable video conferencing tool that makes it easy to connect and collaborate. With features like messaging, file sharing, and app integrations, it’s designed to streamline teamwork. You’ll get high-quality audio and video, strong security with end-to-end encryption, and an intuitive interface—all of which help remote teams and businesses stay productive and connected. Zoom Workplace key features: High-Definition Video & Audio: Provides clear, reliable communication for virtual meetings. End-to-End Encryption: Ensures secure communication with strong data protection. Multi-Factor Authentication: Adds an extra layer of security for user accounts. Integration with Productivity Apps: Supports seamless integration with Microsoft Office, Google Workspace, and more. File Sharing: Easily share files during meetings for efficient collaboration. Real-Time Messaging: Enables team chat for ongoing communication. Collaborative Whiteboarding: Allows teams to brainstorm and collaborate visually. Webinar Support: Host large webinars with interactive features. Administrative Controls: Manage user permissions, meeting settings, and security features. Cloud Storage: Automatically stores meetings and files in the cloud for easy access. Cross-Platform Support: Available on Windows, macOS, and mobile devices. Meeting features: Virtual Backgrounds: Customize your background for meetings to maintain privacy or enhance professionalism. Touch Up My Appearance: Automatically smoothens skin tone for a more polished video appearance. Breakout Rooms: Divide meetings into smaller sessions for group discussions or workshops. Live Transcription: Automatically generate real-time captions during meetings for accessibility. Zoom Apps: Integrate third-party applications directly into Zoom for enhanced functionality. Meeting Reactions: Participants can use emojis for quick, non-verbal feedback during meetings. Polling: Conduct live polls during meetings to gather instant feedback from participants. Attention Tracking: Monitors participant attention during meetings to ensure engagement. Closed Captioning: Enable manual or automatic captions for a more inclusive experience. Webinar Replay: Record and share webinars with analytics for audience engagement. Download: Zoom 64-bit | Zoom 32-bit (Free, paid upgrade available) Links: Zoom Website | Zoom ARM64 | Zoom Installers | Release Notes Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Week One Done
      Rhydderch earned a badge
      Week One Done
    • Experienced
      dismuter went up a rank
      Experienced
    • One Month Later
      mevinyavin earned a badge
      One Month Later
    • Week One Done
      rozermack875 earned a badge
      Week One Done
    • Week One Done
      oneworldtechnologies earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      699
    2. 2
      ATLien_0
      274
    3. 3
      Michael Scrip
      214
    4. 4
      +FloatingFatMan
      186
    5. 5
      Steven P.
      145
  • Tell a friend

    Love Neowin? Tell a friend!