Can't suppress MSVC assertion failure dialog - visual-c++

I've tried this SO answer: How can I disable the debug assertion dialog on Windows?.
Still, no luck.
The code I'm using:
#include <Windows.h>
#include <crtdbg.h>
#include <cassert>
int test(int reportType, char* message, int* returnValue)
{
return 0;
}
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
_CrtSetReportHook(&test);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
//_ASSERT(0); // works as expected: no dialog appears
assert(0); // The dialog appears
return 0;
}
Maybe, there is something wrong with my system's config?

assert documentation notes _set_error_mode should be used:
To override the default output behavior regardless of the app type, call _set_error_mode to select between the output-to-stderr and display-dialog-box behavior.
From their example:
_set_error_mode(_OUT_TO_STDERR);
assert(2+2==5);

Related

Crash system when the module is running

I need to write a module that creates a file and outputs an inscription with a certain frequency. I implemented it. But when this module is running, at some point the system crashes and no longer turns on.
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/kernel.h>
#include <linux/timer.h>
MODULE_LICENSE("GPL");
#define BUF_LEN 255
#define TEXT "Hello from kernel mod\n"
int g_timer_interval = 10000;
static struct file *i_fp;
struct timer_list g_timer;
loff_t offset = 0;
char buff[BUF_LEN + 1] = TEXT;
void timer_rest(struct timer_list *timer)
{
mod_timer(&g_timer, jiffies + msecs_to_jiffies(g_timer_interval));
i_fp = filp_open("/home/hajol/Test.txt", O_RDWR | O_CREAT, 0644);
kernel_write(i_fp, buff, strlen(buff), &offset);
filp_close(i_fp, NULL);
}
static int __init kernel_init(void)
{
timer_setup(&g_timer, timer_rest, 0);
mod_timer(&g_timer, jiffies + msecs_to_jiffies(g_timer_interval));
return 0;
}
static void __exit kernel_exit(void)
{
pr_info("Ending");
del_timer(&g_timer);
}
module_init(kernel_init);
module_exit(kernel_exit);
When the system crashes, you should get a very detailed error message from the kernel, letting you know where and why this happened (the "oops" message):
Read that error message
Read it again
Understand what it means (this often requires starting over from step 1 a couple of times :-) )
One thing that jumps out at me is that you're not going any error checking on the return value of filp_open. So you could very well be feeding a NULL pointer (or error pointer) into kernel_write.

ICU4C austrdup function

I'm trying to run the code demo for ICU4C bellow, and getting
warning: implicit declaration of function 'austrdup'
which subsequently generate an error. I understand that this is due to the missing imported library that contains 'austrdup' function, and have been looking at the source code to guess which one it is, but no luck. Does anyone have any idea which one should be imported?
#include <unicode/umsg.h>
#include <unicode/ustring.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *argv[])
{
UChar* str;
UErrorCode status = U_ZERO_ERROR;
UChar *result = NULL;
UChar pattern[100];
int32_t resultlength, resultLengthOut, i;
double testArgs[] = { 100.0, 1.0, 0.0};
str=(UChar*)malloc(sizeof(UChar) * 10);
u_uastrcpy(str, "MyDisk");
u_uastrcpy(pattern, "The disk {1} contains {0,choice,0#no files|1#one file|1<{0,number,integer} files}");
for(i=0; i<3; i++){
resultlength=0;
resultLengthOut=u_formatMessage( "en_US", pattern, u_strlen(pattern), NULL, resultlength, &status, testArgs[i], str);
if(status==U_BUFFER_OVERFLOW_ERROR){ //check if output truncated
status=U_ZERO_ERROR;
resultlength=resultLengthOut+1;
result=(UChar*)malloc(sizeof(UChar) * resultlength);
u_formatMessage( "en_US", pattern, u_strlen(pattern), result, resultlength, &status, testArgs[i], str);
}
printf("%s\n", austrdup(result) ); //austrdup( a function used to convert UChar* to char*)
free(result);
}
return 0;
}
austrdup is not an official ICU method. It's only used by tests in ICU and defined in icu4c/source/test/cintltst/cintltst.h and implemented in icu4c/source/test/cintltst/cintltst.c. It is bascially just a wrapper around u_austrcpy.

C++ Windows Form Application: Attempted to read or write protected memory (unmanaged class)

I'm trying to use Boost library in my C++ Windows Form Application and I always get an exception:
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
I'm using Visual Studio 2012 and Boost version 1.57.0. Previously I used Boost version 1.56.0 but upgrading didn't solve my issue.
Here are the code:
MyForm.cpp
#include "MyForm.h"
using namespace System;
using namespace System::Windows::Forms;
[STAThread]
void main(cli::array<String^>^ args) {
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
TestUnmanaged::MyForm form;
Application::Run(%form);
}
MyForm.h
#pragma once
#include <iostream>
#include <map>
#include <sstream>
#include <cassert>
#include <stdio.h>
#include "ExternalProfileManager.h"
#define DEFAULT_PROFILE_NAME "profile.bin"
#pragma comment(lib, "Ws2_32.lib")
#pragma comment(lib, "lib/edk.lib")
namespace TestUnmanaged {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
ExternalProfileManager profileManager;
/// <summary>
/// Summary for MyForm
/// </summary>
public ref class MyForm : public System::Windows::Forms::Form
{
public:
MyForm(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
profileManager.load(DEFAULT_PROFILE_NAME);
std::vector<std::string> profileList;
profileManager.listProfile(profileList);
}
ExternalProfileManager.h
#ifndef EXTERNAL_PROFILE_MANAGER_H
#define EXTERNAL_PROFILE_MANAGER_H
#include <boost/serialization/string.hpp>
#include <boost/serialization/map.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/export.hpp>
#include <boost/serialization/tracking.hpp>
#include <boost/serialization/base_object.hpp>
class ExternalProfileManager
{
ExternalProfileManager(const ExternalProfileManager&) {};
ExternalProfileManager& operator = (const ExternalProfileManager&) {};
protected:
std::map<std::string, std::string > _profiles;
typedef std::map<std::string, std::string >::iterator profileItr_t;
// Boost serialization support
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const unsigned int /*file version */)
{
ar & _profiles;
}
public:
ExternalProfileManager();
virtual ~ExternalProfileManager();
virtual bool save(const std::string& location);
virtual bool load(const std::string& location);
virtual bool insertProfile(const std::string& name, const unsigned char* profileBuf, unsigned int bufSize);
virtual bool listProfile(std::vector<std::string>& profiles);
};
//BOOST_CLASS_EXPORT(ExternalProfileManager);
//BOOST_CLASS_TRACKING(ExternalProfileManager, boost::serialization::track_never);
#endif // EXTERNAL_PROFILE_MANAGER_H
ExternalProfileManager.cpp
#include <fstream>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/regex.hpp>
#pragma warning(push)
#pragma warning(disable : 4267) // "conversion from size_t to unsigned int"
#pragma warning(disable : 4996)
#include <boost/archive/archive_exception.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#pragma warning(pop)
#include "ExternalProfileManager.h"
using namespace std;
namespace fs = boost::filesystem;
ExternalProfileManager::ExternalProfileManager()
{
}
ExternalProfileManager::~ExternalProfileManager()
{
}
bool ExternalProfileManager::save(const string& location)
{
ofstream ofs(location.c_str(), ios_base::binary);
if ( !ofs.is_open() ) return false;
try {
boost::archive::binary_oarchive oa(ofs);
oa << *this;
}
catch (boost::archive::archive_exception& )
{
return false;
}
return true;
}
bool ExternalProfileManager::load(const string& location)
{
ifstream ifs(location.c_str(), ios_base::binary);
if ( !ifs.is_open() ) return false;
try {
boost::archive::binary_iarchive ia(ifs);
ia >> *this;
}
catch (boost::archive::archive_exception& )
{
return false;
}
return true;
}
bool ExternalProfileManager::insertProfile(const string& name, const unsigned char* profileBuf, unsigned int bufSize)
{
assert(profileBuf);
// Replace our stored bytes with the contents of the buffer passed by the caller
string bytesIn(profileBuf, profileBuf+bufSize);
_profiles[name] = bytesIn;
return true;
}
bool ExternalProfileManager::listProfile(vector<string>& profiles)
{
profiles.clear();
for ( profileItr_t itr = _profiles.begin(); itr != _profiles.end(); ++itr ) {
profiles.push_back(itr->first);
}
return true;
}
The error occurred in ia >> *this; in ExternalProfileManager::load (thrown in file basic_archive.cpp). So calling profileManager.load(DEFAULT_PROFILE_NAME); from form constructor will trigger the exception.
Calling save will also trigger the same exception but other functions which have no this will work fine.
I tried creating a console application in VS 2012 and call ExternalProfileManager.h and it works perfectly (including save, load, and any other function). Here are the simple console application I created to test it:
Console.cpp
#include <iostream>
#include <map>
#include <sstream>
#include <cassert>
#include <stdio.h>
#include "ExternalProfileManager.h"
#define DEFAULT_PROFILE_NAME "profile.bin"
#pragma comment(lib, "Ws2_32.lib")
#pragma comment(lib, "lib/edk.lib")
ExternalProfileManager profileManager;
int main(int argc, char** argv) {
profileManager.load(DEFAULT_PROFILE_NAME);
std::vector<std::string> profileList;
profileManager.listProfile(profileList);
std::cout << "Available profiles:" << std::endl;
for (size_t i=0; i < profileList.size(); i++) {
std::cout << i+1 << ". " << profileList.at(i);
if (i+1 < profileList.size()) {
std::cout << std::endl;
}
}
return true;
}
profile.bin is generated from calling save function in console application and contain serialized data generated by boost. I can provide the file if it is needed to solve this issue.
I have also tried to create a simple class wrapper but the exception still occurred.
WrapperExternalProfileManager.h
#ifndef WRAPPER_EXTERNAL_PROFILE_MANAGER_H
#define WRAPPER_EXTERNAL_PROFILE_MANAGER_H
#include <string>
#include <vector>
class WrapperExternalProfileManager
{
WrapperExternalProfileManager(const WrapperExternalProfileManager&) {};
WrapperExternalProfileManager& operator = (const WrapperExternalProfileManager&) {};
public:
WrapperExternalProfileManager();
virtual ~WrapperExternalProfileManager();
virtual bool save(const std::string& location);
virtual bool load(const std::string& location);
virtual bool insertProfile(const std::string& name, const unsigned char* profileBuf, unsigned int bufSize);
virtual bool listProfile(std::vector<std::string>& profiles);
};
#endif
WrapperExternalProfileManager.cpp
#include "WrapperExternalProfileManager.h"
#include "ExternalProfileManager.h"
using namespace std;
ExternalProfileManager profileManager;
WrapperExternalProfileManager::WrapperExternalProfileManager()
{
std::cout<<"Constructor WrapperExternalProfileManager"<<std::endl;
}
WrapperExternalProfileManager::~WrapperExternalProfileManager()
{
}
bool WrapperExternalProfileManager::save(const string& location)
{
return profileManager.save(location);
}
bool WrapperExternalProfileManager::load(const string& location)
{
return profileManager.load(location);
}
bool WrapperExternalProfileManager::insertProfile(const string& name, const unsigned char* profileBuf, unsigned int bufSize)
{
return profileManager.insertProfile(name, profileBuf, bufSize);
}
bool WrapperExternalProfileManager::listProfile(vector<string>& profiles)
{
return profileManager.listProfile(profiles);
}
save and load still trigger the exception but other functions work perfectly.
Here are some property of the application which might be helpful:
Linker -> System -> SubSystem: Windows (/SUBSYSTEM:WINDOWS)
General -> Common Language Runtime Support: Common Language Runtime Support (/clr)
I know I have done something incorrectly but I don't know which part. Any suggestion to solve this issue would be appreciated.
Thanks in advance
You're going to have to find the source of your Undefined Behaviour (use static analysis tools, heap checking and divide and conquer).
I've just built your code on VS2013 RTM, using a ultra-simple C# console application as the driver:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var f = new TestUnmanaged.MyForm();
f.ShowDialog();
}
}
}
This JustWorks(TM).
I created a profile.bin with 100 random profiles of varying length:
#if 1
for (int i = 0; i < 100; ++i)
{
std::vector<uint8_t> buf;
std::generate_n(back_inserter(buf), rand() % 1024, rand);
insertProfile("profile" + std::to_string(i), buf.data(), buf.size());
}
save(location);
#endif
And they are deserialized just fine.
Good luck.
Download the full project here http://downloads.sehe.nl/stackoverflow/q27032092.zip in case you want to fiddle with it (compare the details?)

Cuda - printing string from object in __global__ function

I am new to CUDA and I am getting a strange error. I want to print a string from a passed object and I get the error "calling host function from global function is not allowed" and I don't know why. But if I want to print an integer (changing get method to return sk1), everything works fine. Here is the code:
class Duomenys {
private:
string simb;
int sk1;
double sk2;
public:
__device__ __host__ Duomenys(void): simb(""), sk1(0), sk2(0.0) {}
__device__ __host__~Duomenys() {}
__device__ __host__ Duomenys::Duomenys(string simb1, int sk11, double sk21)
: simb(simb1), sk1(sk11), sk2(sk21) {}
__device__ __host__ string Duomenys::get(){
return simb;
}
};
And here I am calling Duomenys::get from __global__ function:
__global__ void Vec_add(Duomenys a) {
printf(" %s \n",a.get());
}
EDIT: I am trying to read data from a file and print it in a global function. In this code I am trying read all data and print just one object to see if everything works. This is the error I'm getting:
calling a __host__ function("std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string") from a __global__ function("Vec_add") is not allowed
Code:
#include <stdio.h>
#include <stdlib.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <sstream>
using namespace std;
class Duomenys {
private:
string simb;
int sk1;
double sk2;
public:
__device__ __host__ Duomenys(void): simb(""), sk1(0), sk2(0.0) {}
__device__ __host__~Duomenys() {}
__device__ __host__ Duomenys::Duomenys(string simb1, int sk11, double sk21)
: simb(simb1), sk1(sk11), sk2(sk21) {}
__device__ __host__ string Duomenys::print()
{
stringstream ss;
ss << left << setw(10) << simb << setw(10) << sk1 << setw(10) << sk2;
return ss.str();
}
};
__global__ void Vec_add(Duomenys a) {
printf(" %s \n",a.print());
}
/* Host code */
int main(int argc, char* argv[]) {
setlocale (LC_ALL,"");
vector<Duomenys> vienas;
vector<vector<Duomenys>> visi;
//data reading to vector "vienas" (it works without any errors)
Duomenys *darr;
const size_t sz = size_t(2) * sizeof(Duomenys);
cudaMalloc((void**)&darr, sz);
Vec_add<<<1, 1>>>(visi[0].at(0));
cudaDeviceSynchronize();
cudaMemcpy(darr, &visi[0].at(0), sz, cudaMemcpyHostToDevice);
return 0;
}
Your problem is not with printf function, but with string data type. You cannot use the C++ string type in a kernel. See related question here: Can we use the string data type in C++ within kernels
Why would you pass a string object to printf when the %s format specifier is expecting something else? When I try to do that in ordinary host code, I get warnings about "passing non-POD types through ellipsis (call will abort at runtime)". Note that this problem has nothing to do with CUDA.
But beyond that issue, presumably you're getting string from the C++ standard library. (It's better if you show a complete reproducer code, then I don't have to guess at where you're getting things or what you are including.)
If I get string as follows:
#include <string>
using namespace std;
Then I am using a function defined in the C++ Standard Library. CUDA supports the C++ language (mostly) but does not necessarily support usage of C++ libraries (or C libraries, for that matter) in device code. Libraries are (usually) composed of (at least some) compiled code (such as allocators, in this case), and this code has been compiled for CPUs, not for the GPU. When you try to use such a CPU compiled routine (e.g. an allocator associated with the string class) in device code, the compiler will bark at you. If you include the complete error message in the question, it will be more obvious specifically what (compiled-for-the-host) function is actually the issue.
Use a standard C style string instead (i.e. char[] and you will be able to use it directly in printf.
EDIT: In response to a question in the comments, here is a modified version of the code posted that demonstrates how to use an ordinary C-style string (i.e. char[]) and print from it in device code.
#include <stdio.h>
#include <stdlib.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <vector>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <sstream>
#define STRSZ 32
using namespace std;
class Duomenys {
private:
char simb[STRSZ];
int sk1;
double sk2;
public:
__device__ __host__ Duomenys(void): sk1(0), sk2(0.0) {}
__device__ __host__~Duomenys() {}
__device__ __host__ Duomenys(char *simb1, int sk11, double sk21)
: sk1(sk11), sk2(sk21) {}
__device__ __host__ char * print()
{
return simb;
}
__device__ __host__ void store_str(const char *str)
{
for (int i=0; i< STRSZ; i++)
simb[i] = str[i];
}
};
__global__ void Vec_add(Duomenys a) {
printf(" %s \n",a.print());
}
/* Host code */
int main(int argc, char* argv[]) {
string host_string("hello\n");
setlocale (LC_ALL,"");
vector<Duomenys> vienas(3);
vienas[0].store_str(host_string.c_str());
vector<vector<Duomenys> > visi(3);
visi[0] = vienas;
//data reading to vector "vienas" (it works without any errors)
Duomenys *darr;
const size_t sz = size_t(2) * sizeof(Duomenys);
cudaMalloc((void**)&darr, sz);
Vec_add<<<1, 1>>>(visi[0].at(0));
cudaDeviceSynchronize();
cudaMemcpy(darr, &(visi[0].at(0)), sz, cudaMemcpyHostToDevice);
return 0;
}
Note that I didn't try to understand your code or fix everything that looked strange to me. However this should demonstrate one possible approach.

I am trying to implement timer using c in ubuntu, but receiving errors of declaration

please help me, i want to implement timer using c in ubunto. i have the written the code but it is giving two errors. I am compiling it using -lrt option of gcc.
Errors i am getting is:
timer1.c: In function ‘main’:
timer1.c:18:52: error: ‘SIG’ undeclared (first use in this function)
timer1.c:18:52: note: each undeclared identifier is reported only once for each function it appears in
timer1.c:21:23: error: ‘handler’ undeclared (first use in this function)
My code is:
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <time.h>
timer_t timerid;
int main(int argc, char *argv[])
{
struct sigevent sev;
struct itimerspec its;
long long freq_nanosecs;
sigset_t mask;
struct sigaction sa;
printf("Establishing handler for signal %d\n", SIG);
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = handler;
sigemptyset(&sa.sa_mask);
sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = SIG;
sev.sigev_value.sival_ptr = &timerid;
printf("timer ID is 0x%lx\n", (long) timerid);
// timer_create(CLOCKID, &sev, &timerid);
/* Start the timer */
its.it_value.tv_sec = 1000;
its.it_value.tv_nsec =0;
its.it_interval.tv_sec = its.it_value.tv_sec;
its.it_interval.tv_nsec = its.it_value.tv_nsec;
timer_settime(timerid,0, &its, NULL);
sleep(10);
}
static void handler(int sig, siginfo_t *si, void *uc)
{
if(si->si_value.sival_ptr != &timerid)
{
printf("Stray signal\n");
}
else
{
printf("Caught signal from timer\n");
}
}
SIG is undeclared because you never declare it, and we can't tell you how to fix it since we don't know what it's supposed to be. handler is undeclared because you forgot the forward declaration. Put a copy of the function signature followed by a semicolon before the function where it's used.
static void handler(int sig, siginfo_t *si, void *uc);
int main(int argc, char *argv[])
{
...

Resources