Windows Structured Exception Handling: simple test program will not compile - winapi

#include <windows.h>
int main()
{
int* i = (int*)malloc(sizeof(int));
*i = 5;
__try
{
free(i);
free(i);
}
__except
{
return -1;
}
return 0;
}
I am trying to learn more about windows SEH. My first test program is giving me some real trouble. I have looked at the msdn documentation and I am still not really sure what I have wrong. I am getting the following errors when I try to compile this program:
error C2059: syntax error : '{'
error C2143: syntax error : missing ';' before '{'
both on line 15.
Thanks.

The problem is the __except clause needs to have an expression. See the following MSDN page for a complete sample
http://msdn.microsoft.com/en-us/library/aa273608(VS.60).aspx
Quick example which will always execute the handler
__try {
// stuff
} __except (EXCEPTION_EXECUTE_HANDLER) {
// handler
}

Related

Trying to load pyd with LoadLibraryEx and got failed

I have a pyd pytest.pyd, where declared two functions: say_hello and add_numbers. So I want to load this pyd dynamically in C++ with LoadLibraryEx. But, when I try to call initpytest func, it fails.
const char* funcname = "initpytest";
HINSTANCE hDLL = LoadLibraryEx(L"D:\\msp\\myproj\\Test\\pytest.pyd", NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
FARPROC p = GetProcAddress(hDLL, funcname);
(*p)(); // fail
In output error: Fatal Python error: PyThreadState_Get: no current thread
Unhandled exception at 0x00007FFCD0CC286E (ucrtbase.dll) in Test.exe: Fatal program exit requested.
Here code of the extension before generating to pyd:
#include "Python.h"
static PyObject* say_hello(PyObject* self, PyObject* args)
{
const char* msg;
if(!PyArg_ParseTuple(args, "s", &msg))
{
return NULL;
}
printf("This is C world\nYour message is %s\n", msg);
return Py_BuildValue("i", 25);
}
static PyObject* add_numbers(PyObject* self, PyObject* args)
{
double a, b;
if (!PyArg_ParseTuple(args, "dd", &a, &b))
{
return NULL;
}
double res = a + b;
return Py_BuildValue("d", res);
}
static PyMethodDef pytest_methods[] = {
{"say_hello", say_hello, METH_VARARGS, "Say Hello!"},
{"add_numbers", add_numbers, METH_VARARGS, "Adding two numbers"},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC initpytest(void)
{
Py_InitModule("pytest", pytest_methods);
}
In the absence of a proper minimal, reproducible example it's impossible to be certain. However, it's probably because you haven't initialized the interpreter: (see this question for example). You need to call Py_Initialize before using any Python functions.
Can I suggest that you use the normal Python C-API tools for running modules (rather than doing it yourself with LoadLibraryEx!) until you fully understand what how embedding Python works. You might consider PyImport_AppendInittab (before initializing) to set up your function directly and avoid the Python search path.

How to print informative error message in a vectored exception handler?

I'm writing a command-line C++ program on Windows, that inevitably sometimes hits an error such as a stack overflow or access violation; in these cases, I would like it to print an informative error message before exiting. This is what I have at the moment:
AddVectoredExceptionHandler(0, handler);
and
LONG WINAPI handler(_EXCEPTION_POINTERS *ExceptionInfo) {
if (ExceptionInfo->ExceptionRecord->ExceptionCode ==
EXCEPTION_STACK_OVERFLOW) {
puts("stack overflow");
ExitProcess(1);
}
printf("exception %X", ExceptionInfo->ExceptionRecord->ExceptionCode);
ExitProcess(1);
}
The special case for stack overflow is because I have found that puts works in that situation but printf doesn't. Is that because there is so little stack space left that only the simplest functions work, or because the stack is damaged in such a way that varargs doesn't work?
Right now, I'm getting exception C0000005. I look at the definitions in minwinbase.h and ntstatus.h and find this is STATUS_ACCESS_VIOLATION. Which is useful to know! It would be even better if I could get more details as well as doing the lookup automatically. I notice the accompanying comment in the header file says
// MessageText:
//
// The instruction at 0x%p referenced memory at 0x%p. The memory could not be %s.
A format string, which suggests this information could be automatically printed. What's the way to do this?
Minimal, complete and verifiable example, compile with cl main.cc:
#include <stdio.h>
#include <windows.h>
LONG WINAPI handler(_EXCEPTION_POINTERS *ExceptionInfo) {
if (ExceptionInfo->ExceptionRecord->ExceptionCode ==
EXCEPTION_STACK_OVERFLOW) {
puts("stack overflow");
ExitProcess(1);
}
printf("exception %X\n", ExceptionInfo->ExceptionRecord->ExceptionCode);
ExitProcess(1);
}
void overflow() { overflow(); }
int main(int argc, const char **argv) {
AddVectoredExceptionHandler(0, handler);
// demonstrate access violation
*(int *)0 = 0;
// demonstrate stack overflow
overflow();
return 0;
}

Expectation failure not triggered if file ends with Boost Spirit Qi parser

When the file ends in the middle of a rule with remaining expectations, it doesn't trigger an expectation error (it does, of course, fail to parse).
A simplified example that triggers the behavior is this:
data_var_decls_r
%= (lit("data")
> lit('{'))
> lit('}');
If the input is only
data {
then the expectation error for the final expected } isn't triggered.
Is there a way to deal with expectation errors that extend past the end of file?
Making it into a self-contained example:
See it Live On Wandbox
#include <boost/spirit/include/qi.hpp>
namespace test {
using namespace boost::spirit::qi;
rule<std::string::const_iterator> rule = lit("data") > '{' > '}';
}
int main() {
std::string const input("data{");
bool ok = parse(input.begin(), input.end(), test::rule);
}
Does throw expectation failure.
Even when using space skipper, it still throws:
See it Live On Wandbox too
#include <boost/spirit/include/qi.hpp>
namespace test {
using namespace boost::spirit::qi;
rule<std::string::const_iterator, space_type> rule = lit("data") > '{' > '}';
}
int main() {
std::string const input("data{");
bool ok = phrase_parse(input.begin(), input.end(), test::rule, test::space);
}

Arduino 1.6.9/1.610 build fails with "'constexprint' does not name a type"

Supposedly Arduino's IDE > 1.6.2 has C++11 support.
I have just freshly downloaded and run version 1.6.9 on OSX (and as others have reported, this repros on Windows as well, with 1.6.9/1.6.10).
I cannot get this simple program to compile:
constexpr int get_five() { return 5; }
void setup() {
Serial.begin(9600);
Serial.println(get_five());
}
void loop() {
}
I receive this error when I try to build or upload:
sketch_jul25a:1: error: 'constexprint' does not name a type
constexpr int get_five() { return 5; }
^
exit status 1
'constexprint' does not name a type
I've looked at this question and answer, but it is supposedly no longer applicable in 1.6.9 version of the IDE that I am using - error: 'constexpr' does not name a type m- arduino ide
I have dug into the temporary files that are output by the IDE when building, and it seems it is trying to automatically generate headers for functions (I assume for multi-file sketch support), and does the wrong thing when it encounters constexpr:
#include <Arduino.h>
#line 1 "/Users/<my_username>/Documents/Arduino/sketch_jul25a/sketch_jul25a.ino"
#line 1 "/Users/<my_username>/Documents/Arduino/sketch_jul25a/sketch_jul25a.ino"
#line 1 "/Users/<my_username>/Documents/Arduino/sketch_jul25a/sketch_jul25a.ino"
constexprint get_five(); // **** <- This looks to be the culprit
#line 3 "/Users/<my_username>/Documents/Arduino/sketch_jul25a/sketch_jul25a.ino"
void setup();
#line 9 "/Users/<my_username>/Documents/Arduino/sketch_jul25a/sketch_jul25a.ino"
void loop();
#line 1 "/Users/<my_username>/Documents/Arduino/sketch_jul25a/sketch_jul25a.ino"
constexpr int get_five() { return 5; }
void setup() {
Serial.begin(9600);
Serial.println(get_five());
}
void loop() {
}
Is this a bug in the Arduino IDE? Is it unique to OSX? Is there a workaround that allows constexpr to work?
In googling I have found that some Arduino libraries are using constexpr, so I am assuming it could be made to work in some cases.
This is a known limitation of the arduino-builder.
Until it is fixed, you can add a prototype yourself above the function. This will prevent the IDE from incorrectly generating its own.
constexpr int get_five();
constexpr int get_five() { return 5; }
void setup() {
Serial.begin(9600);
Serial.println(get_five());
}
void loop() {
}

Why doesn't my freopen function work?

#include <stdio.h>
#include <string.h>
#define MAXN 15
char forbid[MAXN][MAXN];
int dp[2][1<<MAXN],c[1<<MAXN],*dp1,*dp2;
int cnt_one(int x)
{
int s=0;
while(x)
{
s++;
x&=x-1;
}
return s;
}
int main()
{
int t,n,s,a,b,i,j,k;
/*This is my use of freopen function*
************************************/
freopen("datain.txt","r",stdin);
freopen("dataout.txt","w",stdout);
/*This is just a dynamic program to solve a mathematical problem*
****************************************************************/
for(i=0;i<(1<<MAXN);i++) c[i]=cnt_one(i);
scanf("%d",&t);
while(t--)
{
memset(forbid,0,sizeof(forbid));
memset(dp[0],0,sizeof(int)*(1<<MAXN));
dp[0][0]=1;
scanf("%d%d",&n,&s);
while(s--)
{
scanf("%d%d",&a,&b);
forbid[a][b]=1;
}
for(i=1;i<=n;i++)
{
if(i%2)
{
dp1=dp[0];
dp2=dp[1];
}
else
{
dp1=dp[1];
dp2=dp[0];
}
memset(dp2,0,sizeof(int)*(1<<MAXN));
for(j=0;j<(1<<n);j++)
{
if(c[j]!=i-1) continue;
for(k=0;k<n;k++)
{
if(!(j>>k&1)&&!forbid[i][n-k]) dp2[j^(1<<k)]+=dp1[j];
}
}
}
printf("%d\n",dp2[(1<<n)-1]);
}
return 0;
}
This is my program.I used a dynamic program method to solve a mathematical problem.
But when I used the "freopen" function to redirect the "stdout" stream to the file of "dataout.txt",it failed and the file had no data in it.
Could you tell me why I can get the data from "datain.txt" but I can't output data into "dataout.txt"?Is there something wrong with my "freopen" function for "stdout" stream?
I think the problem is that you have a segmentation fault that you will not see. If you place a printf and a return after the freopen I think it will work (works for me).
I would recommend you to use "valgrind" on the resulting executable compiled for debug to see at what line the program crashes. If you want someone to help you further, you need to provide an example input.

Resources