0

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?

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by Ancient Dragon
0

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

0

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);
}

Edited by Ancient Dragon: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.