say i execute an windows api function in my code to allocate memory in the specified process! How do i actually view/know this worked without checking getlasterror() or return codes? is there any other way i can do this in a easier/better manner? maybe runtime with a debugger? if so what would i even need to check for to know it worked successfully?

Recommended Answers

All 2 Replies

Which specific fuction are you talking about? win32 api functions normally return 0 if the function failed.

>>is there any other way i can do this in a easier/better manner
Write your own wrapper for the win32 api function that throws an exception, similar to the one that c++ new operator throws. In that case the program would have to use try/catch blocks

Example

#include<iostream>
#include <vector>
#include <typeinfo>
#include <limits>
#include <Windows.h>

struct mymem
{
    HGLOBAL hGlbal;
    void* hGlobalPtr;
};

std::vector<mymem> myallocs;

void* MyAllocMem(size_t size)
{
    HGLOBAL hGlobal = GlobalAlloc(GHND, size);
    if( hGlobal == NULL)
    {
        std::bad_alloc e;
        throw(e);
    }
    void* v =  GlobalLock(hGlobal);
    mymem m = {hGlobal,v};
    myallocs.push_back(m);
    return v;
}

void MyFree(void* ptr)
{
    std::vector<mymem>::iterator it = myallocs.begin();
    for(; it != myallocs.end(); it++)
    {
        if( (*it).hGlobalPtr == ptr)
        {
            GlobalFree((*it).hGlbal);
            myallocs.erase(it);
            break;
        }
    }
}

int main()
{
    int* ay;
    try
    {
        ay = (int *)MyAllocMem(ULONG_MAX);
    }
    catch(std::bad_alloc& ba)
    {
        std::cerr << "bad_alloc caught: " << ba.what() << std::endl;
    }
    MyFree(ay);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.