clang not working properly for C++ Exceptions - clang

struct ZeroError{
int err;
ZeroError(int e){err = e;}
};
int div(int a,int b)
{
if (b == 0)throw int(10);
return a/b;
}
int main()
{
try{
int x = div(10,0);
cout<< x;
}
catch(int z){
cout<<z;
}
}
even though exception is caught when i run the program i am getting
terminate called after throwing an instance of 'int'
This application has requested the Runtime to terminate it in an
unusual way. Please contact the application's support team for more
information.

Try compiling with -fcxx-exceptions.
Did a little cleanup on your code, using div as a function name collided with one in stdlib.h. Also tried to make the error output more distinctive.
#include <iostream>
#include <exception>
using namespace std;
struct ZeroError{
int err;
ZeroError(int e){err = e;}
};
int divide(int a,int b)
{
if (b == 0)throw int(10);
return a/b;
}
int main()
{
try{
int x = divide(10,0);
cout << x << endl;
}
catch(int z){
cout << "Exception: " << z << endl;
}
}
Compiling with the flag seems to work great:
% clang++ -fcxx-exceptions foo.cc
% ./a.out
Exception: 10
% clang++ --version
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.1.0
Thread model: posix

Related

How to get stack trace for C/C++ program in CYGWIN environment?

How to get stack trace for C/C++ program in CYGWIN environment ?
** I was looking for a back trace mechanism, I've compiled some of the solutions found here and made it a small program for quick reference.
My Answers with a code snippet:
#if defined(__CYGWIN__)
#include <Windows.h>
#include <dbghelp.h>
#include <psdk_inc/_dbg_common.h>
#include <cxxabi.h>
#include <cstring>
class Error // Windows version
{
private:
void *stacktrace[MAX_STACKTRACE_SIZE];
size_t stacktrace_size;
public:
const char* message;
Error(const char* m)
: message(m)
, stacktrace_size(0)
{
// Capture the stack, when error is 'hit'
stacktrace_size = CaptureStackBackTrace(0, MAX_STACKTRACE_SIZE, stacktrace, nullptr);
}
void print_backtrace(ostream& out) const
{
SYMBOL_INFO * symbol;
HANDLE process;
size_t length;
process = GetCurrentProcess();
SymInitialize(process, nullptr, TRUE);
symbol = (SYMBOL_INFO *)calloc(sizeof(SYMBOL_INFO) + 256 * sizeof(char), 1);
symbol->MaxNameLen = 255;
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
length = strlen (symbol->Name);
std::string result;
char tempStr[255] = {0};
for (int i = 0; i < stacktrace_size; i++)
{
int status = 0;
// '_' is missing in symbol->Name , hence prefix it and concat with symbol->Name
char prefixed_symbol [256] = "_" ;
SymFromAddr(process, (DWORD64)(stacktrace[i]), 0, symbol);
auto backtrace_line = string(symbol->Name);
if (backtrace_line.size() == 0) continue;
// https://en.wikipedia.org/wiki/Name_mangling
// Prefix '_' with symbol name, so that __cxa_demangle does the job correctly
// $ c++filt -n _Z9test_ringI12SmallIntegerIhEEvRK4RingIT_E
strcat (prefixed_symbol, symbol->Name);
char * demangled_name = abi::__cxa_demangle(prefixed_symbol, nullptr, nullptr, &status);
if(status < 0)
{
sprintf(tempStr, "%i: %s - 0x%0X\n", stacktrace_size-i-1, symbol->Name, symbol->Address);
// out << symbol->Name << endl;
}
else
{
sprintf(tempStr, "%i: %s - 0x%0X\n", stacktrace_size - i - 1, demangled_name, symbol->Address);
// out << demangled_name << endl;
}
// Append the extracted info to the result
result += tempStr;
// Free the HEAP allocation made by __cxa_demangle
free((void*)demangled_name);
// Restore the prefix '_' string
prefixed_symbol [1] = '\0';
}
std::cout << result << std::endl;
free(symbol);
}
};
int main ()
{
try {
do_something ();
if (false == status) throw Error("SystemError");
}
catch (const Error &error)
{
cout << "NotImplementedError(\"" << error.message << "\")" << endl;
error.print_backtrace(cout);
return 1;
}
#endif
Command Line Option:
// Use -limagehlp to link the library
g++ -std=c++20 main.cpp -limagehlp

Unable to copy a .png(image) file in the system in c++ can anyone help me how to do this? [duplicate]

I search for a good way to copy a file (binary or text). I've written several samples, everyone works. But I want hear the opinion of seasoned programmers.
I missing good examples and search a way which works with C++.
ANSI-C-WAY
#include <iostream>
#include <cstdio> // fopen, fclose, fread, fwrite, BUFSIZ
#include <ctime>
using namespace std;
int main() {
clock_t start, end;
start = clock();
// BUFSIZE default is 8192 bytes
// BUFSIZE of 1 means one chareter at time
// good values should fit to blocksize, like 1024 or 4096
// higher values reduce number of system calls
// size_t BUFFER_SIZE = 4096;
char buf[BUFSIZ];
size_t size;
FILE* source = fopen("from.ogv", "rb");
FILE* dest = fopen("to.ogv", "wb");
// clean and more secure
// feof(FILE* stream) returns non-zero if the end of file indicator for stream is set
while (size = fread(buf, 1, BUFSIZ, source)) {
fwrite(buf, 1, size, dest);
}
fclose(source);
fclose(dest);
end = clock();
cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
cout << "CPU-TIME START " << start << "\n";
cout << "CPU-TIME END " << end << "\n";
cout << "CPU-TIME END - START " << end - start << "\n";
cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";
return 0;
}
POSIX-WAY (K&R use this in "The C programming language", more low-level)
#include <iostream>
#include <fcntl.h> // open
#include <unistd.h> // read, write, close
#include <cstdio> // BUFSIZ
#include <ctime>
using namespace std;
int main() {
clock_t start, end;
start = clock();
// BUFSIZE defaults to 8192
// BUFSIZE of 1 means one chareter at time
// good values should fit to blocksize, like 1024 or 4096
// higher values reduce number of system calls
// size_t BUFFER_SIZE = 4096;
char buf[BUFSIZ];
size_t size;
int source = open("from.ogv", O_RDONLY, 0);
int dest = open("to.ogv", O_WRONLY | O_CREAT /*| O_TRUNC/**/, 0644);
while ((size = read(source, buf, BUFSIZ)) > 0) {
write(dest, buf, size);
}
close(source);
close(dest);
end = clock();
cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
cout << "CPU-TIME START " << start << "\n";
cout << "CPU-TIME END " << end << "\n";
cout << "CPU-TIME END - START " << end - start << "\n";
cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";
return 0;
}
KISS-C++-Streambuffer-WAY
#include <iostream>
#include <fstream>
#include <ctime>
using namespace std;
int main() {
clock_t start, end;
start = clock();
ifstream source("from.ogv", ios::binary);
ofstream dest("to.ogv", ios::binary);
dest << source.rdbuf();
source.close();
dest.close();
end = clock();
cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
cout << "CPU-TIME START " << start << "\n";
cout << "CPU-TIME END " << end << "\n";
cout << "CPU-TIME END - START " << end - start << "\n";
cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";
return 0;
}
COPY-ALGORITHM-C++-WAY
#include <iostream>
#include <fstream>
#include <ctime>
#include <algorithm>
#include <iterator>
using namespace std;
int main() {
clock_t start, end;
start = clock();
ifstream source("from.ogv", ios::binary);
ofstream dest("to.ogv", ios::binary);
istreambuf_iterator<char> begin_source(source);
istreambuf_iterator<char> end_source;
ostreambuf_iterator<char> begin_dest(dest);
copy(begin_source, end_source, begin_dest);
source.close();
dest.close();
end = clock();
cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
cout << "CPU-TIME START " << start << "\n";
cout << "CPU-TIME END " << end << "\n";
cout << "CPU-TIME END - START " << end - start << "\n";
cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";
return 0;
}
OWN-BUFFER-C++-WAY
#include <iostream>
#include <fstream>
#include <ctime>
using namespace std;
int main() {
clock_t start, end;
start = clock();
ifstream source("from.ogv", ios::binary);
ofstream dest("to.ogv", ios::binary);
// file size
source.seekg(0, ios::end);
ifstream::pos_type size = source.tellg();
source.seekg(0);
// allocate memory for buffer
char* buffer = new char[size];
// copy file
source.read(buffer, size);
dest.write(buffer, size);
// clean up
delete[] buffer;
source.close();
dest.close();
end = clock();
cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
cout << "CPU-TIME START " << start << "\n";
cout << "CPU-TIME END " << end << "\n";
cout << "CPU-TIME END - START " << end - start << "\n";
cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";
return 0;
}
LINUX-WAY // requires kernel >= 2.6.33
#include <iostream>
#include <sys/sendfile.h> // sendfile
#include <fcntl.h> // open
#include <unistd.h> // close
#include <sys/stat.h> // fstat
#include <sys/types.h> // fstat
#include <ctime>
using namespace std;
int main() {
clock_t start, end;
start = clock();
int source = open("from.ogv", O_RDONLY, 0);
int dest = open("to.ogv", O_WRONLY | O_CREAT /*| O_TRUNC/**/, 0644);
// struct required, rationale: function stat() exists also
struct stat stat_source;
fstat(source, &stat_source);
sendfile(dest, source, 0, stat_source.st_size);
close(source);
close(dest);
end = clock();
cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
cout << "CPU-TIME START " << start << "\n";
cout << "CPU-TIME END " << end << "\n";
cout << "CPU-TIME END - START " << end - start << "\n";
cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";
return 0;
}
Environment
GNU/LINUX (Archlinux)
Kernel 3.3
GLIBC-2.15, LIBSTDC++ 4.7 (GCC-LIBS), GCC 4.7, Coreutils 8.16
Using RUNLEVEL 3 (Multiuser, Network, Terminal, no GUI)
INTEL SSD-Postville 80 GB, filled up to 50%
Copy a 270 MB OGG-VIDEO-FILE
Steps to reproduce
1. $ rm from.ogg
2. $ reboot # kernel and filesystem buffers are in regular
3. $ (time ./program) &>> report.txt # executes program, redirects output of program and append to file
4. $ sha256sum *.ogv # checksum
5. $ rm to.ogg # remove copy, but no sync, kernel and fileystem buffers are used
6. $ (time ./program) &>> report.txt # executes program, redirects output of program and append to file
Results (CPU TIME used)
Program Description UNBUFFERED|BUFFERED
ANSI C (fread/frwite) 490,000|260,000
POSIX (K&R, read/write) 450,000|230,000
FSTREAM (KISS, Streambuffer) 500,000|270,000
FSTREAM (Algorithm, copy) 500,000|270,000
FSTREAM (OWN-BUFFER) 500,000|340,000
SENDFILE (native LINUX, sendfile) 410,000|200,000
Filesize doesn't change.
sha256sum print the same results.
The video file is still playable.
Questions
What method would you prefer?
Do you know better solutions?
Do you see any mistakes in my code?
Do you know a reason to avoid a solution?
FSTREAM (KISS, Streambuffer)
I really like this one, because it is really short and simple. As far is I know the operator << is overloaded for rdbuf() and doesn't convert anything. Correct?
Thanks
Update 1
I changed the source in all samples in that way, that the open and close of the file descriptors is include in the measurement of clock(). Their are no other significant changes in the source code. The results doesn't changed! I also used time to double-check my results.
Update 2
ANSI C sample changed: The condition of the while-loop doesn't call any longer feof() instead I moved fread() into the condition. It looks like, the code runs now 10,000 clocks faster.
Measurement changed: The former results were always buffered, because I repeated the old command line rm to.ogv && sync && time ./program for each program a few times. Now I reboot the system for every program. The unbuffered results are new and show no surprise. The unbuffered results didn't changed really.
If i don't delete the old copy, the programs react different. Overwriting a existing file buffered is faster with POSIX and SENDFILE, all other programs are slower. Maybe the options truncate or create have a impact on this behaviour. But overwriting existing files with the same copy is not a real world use-case.
Performing the copy with cp takes 0.44 seconds unbuffered und 0.30 seconds buffered. So cp is a little bit slower than the POSIX sample. Looks fine for me.
Maybe I add also samples and results of mmap() and copy_file() from boost::filesystem.
Update 3
I've put this also on a blog page and extended it a little bit. Including splice(), which is a low-level function from the Linux kernel. Maybe more samples with Java will follow.
http://www.ttyhoney.com/blog/?page_id=69
Copy a file in a sane way:
#include <fstream>
int main()
{
std::ifstream src("from.ogv", std::ios::binary);
std::ofstream dst("to.ogv", std::ios::binary);
dst << src.rdbuf();
}
This is so simple and intuitive to read it is worth the extra cost. If we were doing it a lot, better to fall back on OS calls to the file system. I am sure boost has a copy file method in its filesystem class.
There is a C method for interacting with the file system:
#include <copyfile.h>
int
copyfile(const char *from, const char *to, copyfile_state_t state, copyfile_flags_t flags);
With C++17 the standard way to copy a file will be including the <filesystem> header and using:
bool copy_file( const std::filesystem::path& from,
const std::filesystem::path& to);
bool copy_file( const std::filesystem::path& from,
const std::filesystem::path& to,
std::filesystem::copy_options options);
The first form is equivalent to the second one with copy_options::none used as options (see also copy_file).
The filesystem library was originally developed as boost.filesystem and finally merged to ISO C++ as of C++17.
Too many!
The "ANSI C" way buffer is redundant, since a FILE is already buffered. (The size of this internal buffer is what BUFSIZ actually defines.)
The "OWN-BUFFER-C++-WAY" will be slow as it goes through fstream, which does a lot of virtual dispatching, and again maintains internal buffers or each stream object. (The "COPY-ALGORITHM-C++-WAY" does not suffer this, as the streambuf_iterator class bypasses the stream layer.)
I prefer the "COPY-ALGORITHM-C++-WAY", but without constructing an fstream, just create bare std::filebuf instances when no actual formatting is needed.
For raw performance, you can't beat POSIX file descriptors. It's ugly but portable and fast on any platform.
The Linux way appears to be incredibly fast — perhaps the OS let the function return before I/O was finished? In any case, that's not portable enough for many applications.
EDIT: Ah, "native Linux" may be improving performance by interleaving reads and writes with asynchronous I/O. Letting commands pile up can help the disk driver decide when is best to seek. You might try Boost Asio or pthreads for comparison. As for "can't beat POSIX file descriptors"… well that's true if you're doing anything with the data, not just blindly copying.
I want to make the very important note that the LINUX method using sendfile() has a major problem in that it can not copy files more than 2GB in size! I had implemented it following this question and was hitting problems because I was using it to copy HDF5 files that were many GB in size.
http://man7.org/linux/man-pages/man2/sendfile.2.html
sendfile() will transfer at most 0x7ffff000 (2,147,479,552) bytes,
returning the number of bytes actually transferred. (This is true on
both 32-bit and 64-bit systems.)
Qt has a method for copying files:
#include <QFile>
QFile::copy("originalFile.example","copiedFile.example");
Note that to use this you have to install Qt (instructions here) and include it in your project (if you're using Windows and you're not an administrator, you can download Qt here instead). Also see this answer.
For those who like boost:
boost::filesystem::path mySourcePath("foo.bar");
boost::filesystem::path myTargetPath("bar.foo");
// Variant 1: Overwrite existing
boost::filesystem::copy_file(mySourcePath, myTargetPath, boost::filesystem::copy_option::overwrite_if_exists);
// Variant 2: Fail if exists
boost::filesystem::copy_file(mySourcePath, myTargetPath, boost::filesystem::copy_option::fail_if_exists);
Note that boost::filesystem::path is also available as wpath for Unicode. And that you could also use
using namespace boost::filesystem
if you do not like those long type names
I'm not quite sure what a "good way" of copying a file is, but assuming "good" means "fast", I could broaden the subject a little.
Current operating systems have long been optimized to deal with run of the mill file copy. No clever bit of code will beat that. It is possible that some variant of your copy techniques will prove faster in some test scenario, but they most likely would fare worse in other cases.
Typically, the sendfile function probably returns before the write has been committed, thus giving the impression of being faster than the rest. I haven't read the code, but it is most certainly because it allocates its own dedicated buffer, trading memory for time. And the reason why it won't work for files bigger than 2Gb.
As long as you're dealing with a small number of files, everything occurs inside various buffers (the C++ runtime's first if you use iostream, the OS internal ones, apparently a file-sized extra buffer in the case of sendfile). Actual storage media is only accessed once enough data has been moved around to be worth the trouble of spinning a hard disk.
I suppose you could slightly improve performances in specific cases. Off the top of my head:
If you're copying a huge file on the same disk, using a buffer bigger than the OS's might improve things a bit (but we're probably talking about gigabytes here).
If you want to copy the same file on two different physical destinations you will probably be faster opening the three files at once than calling two copy_file sequentially (though you'll hardly notice the difference as long as the file fits in the OS cache)
If you're dealing with lots of tiny files on an HDD you might want to read them in batches to minimize seeking time (though the OS already caches directory entries to avoid seeking like crazy and tiny files will likely reduce disk bandwidth dramatically anyway).
But all that is outside the scope of a general purpose file copy function.
So in my arguably seasoned programmer's opinion, a C++ file copy should just use the C++17 file_copy dedicated function, unless more is known about the context where the file copy occurs and some clever strategies can be devised to outsmart the OS.
The simplest way in C++17 and later is:
Use the #include <filesystem> and copy() method. There are 4 overloads for the copy method. You can check that in this link
void copy( const std::filesystem::path& from,
const std::filesystem::path& to );
void copy( const std::filesystem::path& from,
const std::filesystem::path& to,
std::error_code& ec );
void copy( const std::filesystem::path& from,
const std::filesystem::path& to,
std::filesystem::copy_options options );
void copy( const std::filesystem::path& from,
const std::filesystem::path& to,
std::filesystem::copy_options options,
std::error_code& ec );
With copy() method can copy files and directories with some options like recursive, non-recursive, copy only directories or overwrite or skip existing files, and so on. you can read more about copy options in this link
This is a sample code from here with some edit:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
// create directories. create all directories if not exist.
fs::create_directories("sandbox/dir/subdir");
// create file with content 'a'
std::ofstream("sandbox/file1.txt").put('a');
// copy file
fs::copy("sandbox/file1.txt", "sandbox/file2.txt");
// copy directory (non-recursive)
fs::copy("sandbox/dir", "sandbox/dir2");
// copy directory (recursive)
const auto copyOptions = fs::copy_options::update_existing
| fs::copy_options::recursive
;
fs::copy("sandbox", "sandbox_copy", copyOptions);
// remove sanbox directory and all sub directories and sub files.
fs::remove_all("sandbox");
}
In theory, the most efficient way to copy files is to use a memory map, so the copying process can be done entirely in kernel mode.
If the file is smaller than 2GB, you can use the following code on Unix platforms:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
int main(int argc, char **argv) {
if (argc != 3) {
fprintf(stderr, "usage: %s <source> <target>\n", argv[0]);
return EXIT_FAILURE;
}
int source_fd = open(argv[1], O_RDONLY, 0);
if (source_fd < 0) {
perror("open source");
return EXIT_FAILURE;
}
int target_fd = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, 0666);
if (target_fd < 0) {
perror("open target");
return EXIT_FAILURE;
}
struct stat stat;
int r = fstat(source_fd, &stat);
if (r < 0) {
perror("fstat");
return EXIT_FAILURE;
}
char *buf = mmap(NULL, stat.st_size, PROT_READ, MAP_PRIVATE, source_fd, 0);
if (buf == MAP_FAILED) {
perror("mmap");
return EXIT_FAILURE;
}
r = write(target_fd, buf, stat.st_size);
if (r < 0) {
perror("write");
return EXIT_FAILURE;
} else if (r != stat.st_size) {
fprintf(stderr, "write: copied file truncated to %d bytes\n", r);
return EXIT_FAILURE;
} else {
printf("write: %d bytes copied\n", r);
}
munmap(buf, stat.st_size);
close(source_fd);
close(target_fd);
return EXIT_SUCCESS;
}
Copying a 2GB file, the time usage is:
real 0m1.842s
user 0m0.000s
sys 0m1.505s
But if the file size is larger than 2GB, write() will truncate the file to 2GB, so it cannot be used. We must map the destination file and use memcpy to copy the file. Since memcpy is used, we can see there is time spent in user mode.
Here is a universal version:
import sys
import mmap
if len(sys.argv) != 3:
print(f'Usage: {sys.argv[0]} <source> <destination>')
sys.exit(1)
with open(sys.argv[1], 'rb') as src, open(sys.argv[2], 'wb') as dst:
mmapped_src = mmap.mmap(src.fileno(), 0, access=mmap.ACCESS_READ)
print(f"{dst.write(mmapped_src)} bytes written")
mmapped_src.close()
Copying a 3.2GB file, the time usage is:
real 0m4.426s
user 0m0.030s
sys 0m2.793s
Here is a Unix version:
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
int src_fd, dst_fd;
void *src_map, *dst_map;
struct stat src_stat;
if (argc != 3) {
printf("Usage: %s <source> <destination>\n", argv[0]);
return 1;
}
src_fd = open(argv[1], O_RDONLY);
if (src_fd == -1) {
perror("open source");
return 1;
}
if (fstat(src_fd, &src_stat) == -1) {
perror("fstat");
return 1;
}
src_map = mmap(NULL, src_stat.st_size, PROT_READ, MAP_PRIVATE, src_fd, 0);
if (src_map == MAP_FAILED) {
perror("mmap source");
return 1;
}
dst_fd = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, src_stat.st_mode);
if (dst_fd == -1) {
perror("open destination");
return 1;
}
if (ftruncate(dst_fd, src_stat.st_size) == -1) {
perror("ftruncate");
return 1;
}
dst_map = mmap(NULL, src_stat.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, dst_fd, 0);
if (dst_map == MAP_FAILED) {
perror("mmap destination");
return 1;
}
memcpy(dst_map, src_map, src_stat.st_size);
printf("Copied %ld bytes from %s to %s\n", src_stat.st_size, argv[1], argv[2]);
munmap(src_map, src_stat.st_size);
munmap(dst_map, src_stat.st_size);
close(src_fd);
close(dst_fd);
return 0;
}
Copying a 3.2GB file, the time usage is:
real 0m3.365s
user 0m0.788s
sys 0m2.471s
Here is a Windows version:
#include <stdio.h>
#include <windows.h>
void PrintLastError(const char *name) {
char *msg;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR) &msg, 0, NULL);
fprintf(stderr, "%s: %s", name, msg);
LocalFree(msg);
exit(1);
}
int main(int argc, char* argv[]) {
HANDLE hSrc, hDst;
HANDLE hSrcMap, hDstMap;
LPVOID lpSrcMap, lpDstMap;
DWORD dwSrcSize, dwDstSize;
if (argc != 3) {
printf("Usage: %s <source> <destination>\n", argv[0]);
return 1;
}
hSrc = CreateFile(argv[1], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hSrc == INVALID_HANDLE_VALUE) {
PrintLastError("CreateFile");
return 1;
}
dwSrcSize = GetFileSize(hSrc, NULL);
if (dwSrcSize == INVALID_FILE_SIZE) {
PrintLastError("GetFileSize");
goto SRC_MAP_FAIL;
}
hSrcMap = CreateFileMapping(hSrc, NULL, PAGE_READONLY, 0, 0, NULL);
if (hSrcMap == NULL) {
PrintLastError("CreateFileMapping");
goto SRC_MAP_FAIL;
}
lpSrcMap = MapViewOfFile(hSrcMap, FILE_MAP_READ, 0, 0, 0);
if (lpSrcMap == NULL) {
PrintLastError("MapViewOfFile");
goto SRC_VIEW_FAIL;
}
hDst = CreateFile(argv[2], GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hDst == INVALID_HANDLE_VALUE) {
PrintLastError("CreateFile");
goto DEST_OPEN_FAIL;
}
dwDstSize = dwSrcSize;
hDstMap = CreateFileMapping(hDst, NULL, PAGE_READWRITE, 0, dwDstSize, NULL);
if (hDstMap == NULL) {
PrintLastError("CreateFileMapping");
goto DEST_MAP_FAIL;
}
lpDstMap = MapViewOfFile(hDstMap, FILE_MAP_WRITE, 0, 0, 0);
if (lpDstMap == NULL) {
PrintLastError("MapViewOfFile");
goto DEST_VIEW_FAIL;
}
memcpy(lpDstMap, lpSrcMap, dwSrcSize);
printf("Copied %lu bytes from %s to %s", dwSrcSize, argv[1], argv[2]);
UnmapViewOfFile(lpDstMap);
DEST_VIEW_FAIL:
CloseHandle(hDstMap);
DEST_MAP_FAIL:
CloseHandle(hDst);
DEST_OPEN_FAIL:
UnmapViewOfFile(lpSrcMap);
SRC_VIEW_FAIL:
CloseHandle(hSrcMap);
SRC_MAP_FAIL:
CloseHandle(hSrc);
return 0;
}

OpenCV / HighGUI draws new windows for each attached object

I'm working through Learning OpenCV 3 by Kaehler & Bradski.
I've applied all errata fixes to this code per http://www.oreilly.com/catalog/errata.csp?isbn=0636920044765.
Expected behavior: the trackbar should be attached to the namedWindow "Example2-4", then frames from a video file (specified via command-line argument) should be drawn in the same window.
Actual behavior: the trackbar is drawn in one window named "Example2-4", then the frames are drawn in a second window named "Example2-4". Closing either window causes the program to hang. Otherwise the behavior is correct.
Platform: Windows 10, x64, OpenCV 3.3
Edit 1:
I tried adding a string literal to the top of main():
char *window_name = "Window";
and replacing every instance of "Example2-4" with window_name. This didn't change the behavior.
Edit 2:
This code is the first time I've tried to add an interactive widget, but adding images and video frames to windows in previous examples also generated two windows with the same name. I suspect I'm up against a configuration issue, but I still have no idea how to solve it.
Edit 3: I've added code for the simplest program that will demonstrate the problem behavior, and changed the title of this post to characterize it better.
Code:
/* Windows precompiled headers */
//#include "stdafx.h"
/* C++ */
#include <iostream>
#include <fstream>
/* OpenCv */
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace std;
int g_slider_position = 0;
int g_run = 1, g_dontset = 0; // start out in single step mode
cv::VideoCapture g_cap;
void onTrackBarSlide(int pos, void *);
int main(int argc, char **argv)
{
cv::namedWindow("Example2-4", CV_WINDOW_AUTOSIZE);
g_cap.open(string(argv[1]));
int frames = (int)g_cap.get(CV_CAP_PROP_FRAME_COUNT);
int tmpw = (int)g_cap.get(CV_CAP_PROP_FRAME_WIDTH);
int tmph = (int)g_cap.get(CV_CAP_PROP_FRAME_HEIGHT);
cout << "Video has " << frames << " frames of dimensions ("
<< tmpw << ", " << tmph << ")." << endl;
cv::createTrackbar("Position", "Example2-4", &g_slider_position, frames,
onTrackBarSlide);
cv::Mat frame;
for (;;) {
if (g_run != 0) {
g_cap >> frame;
if (frame.empty())
break;
int current_pos = (int)g_cap.get(CV_CAP_PROP_POS_FRAMES);
g_dontset = 1;
cv::setTrackbarPos("Position", "Example2-4", current_pos);
cv::imshow("Example2-4", frame);
g_run -= 1;
}
char c = (char)cv::waitKey(10);
if (c == 's') { // single step
g_run = 1;
cout << "Single step, run = " << g_run << endl;
}
if (c == 'r') { // run mode
g_run = -1;
cout << "Run mode, run = " << g_run << endl;
}
if (c == 27)
break;
}
return 0;
}
void onTrackBarSlide(int pos, void *) {
g_cap.set(CV_CAP_PROP_POS_FRAMES, pos);
if (!g_dontset)
g_run = 1;
g_dontset = 0;
}
Simplest code which results in problem behavior. Gets an image via command line argument:
#include <opencv2\opencv.hpp>
int main(int argc, char **argv)
{
char *window_name = "Window";
cv::Mat img = cv::imread(argv[1], -1);
if (img.empty())
return -1;
cv::namedWindow(window_name, CV_WINDOW_AUTOSIZE);
cv::imshow(window_name, img);
cv::waitKey(0);
cv::destroyWindow(window_name);
return 0;
}

Possible bug in libc++ for mac os ,string destructor is not called when string obj goes out of scope

In libc++ i have found that basic_string destructor does not gets called , once string goes out of the scope the memory is freed by calling delete operator rather than calling its destructor and then calling the delete operator from destructor, why so?
Can some one explain this?
see the sample program
void * operator new ( size_t len ) throw ( std::bad_alloc )
{
void * mem = malloc( len );
if ( (mem == 0) && (len != 0) )
throw std::bad_alloc();
return mem;
}
void operator delete ( void * ptr ) throw()
{
if ( ptr != 0 )
free( ptr );
}
int main(int argc, const char * argv[])
{
std::string mystr("testing very very very big string for string class");
std::string mystr2(mystr1.begin(),mystr.end());
}
Put break point on new and delete and then check the call stack.
new operator gets called from basic_string class while the delete gets called from the end of main, while ideally basic_string destructor should have called first and then the delete operator should be called via deallocate call of allocator, this is valid for 2nd string creation.
I'm seeing the same thing in the debugger that you are; I don't know for sure, but I suspect that stuff is getting inlined. The destructor for basic_string is very small; a single test (for the small string optimization), and then a call to the allocator's deallocate function (through allocate_traits). std::allocators allocate function is also quite small, just a wrapper around operator delete.
You could test this by writing your own allocator. (Later: see below)
More stuff that I generated while investigating this question; read on if you're interested.
[Note: there's a bug in your code - in the second line you wrote: mystr1.begin(),mystr.end()) - where is mystr1 declared?]
Assuming that's a typo, I tried some slightly different code:
#include <string>
#include <new>
#include <iostream>
int news = 0;
int dels = 0;
void * operator new ( size_t len ) throw ( std::bad_alloc )
{
void * mem = malloc( len );
if ( (mem == 0) && (len != 0) )
throw std::bad_alloc();
++news;
return mem;
}
void operator delete ( void * ptr ) throw()
{
++dels;
if ( ptr != 0 )
free( ptr );
}
int main(int argc, const char * argv[])
{
{
std::string mystr("testing very very very big string for string class");
std::string mystr2(mystr.begin(),mystr.end());
std::cout << "News = " << news << "; Dels = " << dels << std::endl;
}
std::cout << "News = " << news << "; Dels = " << dels << std::endl;
}
If you run this code, it prints (at least for me):
News = 2; Dels = 0
News = 2; Dels = 2
which is exactly what it should.
If I toss the code into compiler explorer, then I see both the calls to basic_string::~basic_string(), exactly as I expect. (Well, I see three of them, but one of them is in an exception handling block, which ends with a call to _Unwind_resume).
Later - this code:
#include <string>
#include <new>
#include <iostream>
int news = 0;
int dels = 0;
template <class T>
class MyAllocator
{
public:
typedef T value_type;
MyAllocator() noexcept {}
template <class U>
MyAllocator(MyAllocator<U>) noexcept {}
T* allocate(std::size_t n)
{
++news;
return static_cast<T*>(::operator new(n*sizeof(T)));
}
void deallocate(T* p, std::size_t)
{
++dels;
return ::operator delete(static_cast<void*>(p));
}
friend bool operator==(MyAllocator, MyAllocator) {return true;}
friend bool operator!=(MyAllocator, MyAllocator) {return false;}
};
int main(int argc, const char * argv[])
{
{
typedef std::basic_string<char, std::char_traits<char>, MyAllocator<char>> S;
S mystr("testing very very very big string for string class");
S mystr2(mystr.begin(),mystr.end());
std::cout << "Allocator News = " << news << "; Allocator Dels = " << dels << std::endl;
}
std::cout << "Allocator News = " << news << "; Allocator Dels = " << dels << std::endl;
}
prints:
Allocator News = 2; Allocator Dels = 0
Allocator News = 2; Allocator Dels = 2
which confirms that the allocator is getting called.

lua5.2's error: multiple Lua VMs detected

I use 5.2 for learning recently, what I want to try like this:
Step 1, build a c module for lua:
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include <stdlib.h>
static int add(lua_State *L) {
int x = luaL_checkint(L, -2);
int y = luaL_checkint(L, -1);
lua_pushinteger(L, x + y);
return 1;
}
static const struct luaL_Reg reg_lib[] = {
{"add", add}
};
int luaopen_tool(lua_State *L) {
luaL_newlib(L, reg_lib);
lua_setglobal(L, "tool");
return 0;
}
I compile and link it with liblua.a, and I'm sure it works well in lua script like "require("tool") tool.add(1, 2)"
Step 2, I write another C program that wants to require my c module in step 1 like this:
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include <stdlib.h>
int main(int argc, char* const argv[]) {
lua_State *L = luaL_newstate();
luaL_requiref(L, "base", luaopen_base, 1);
luaL_requiref(L, "package", luaopen_package, 1);
lua_getglobal(L, "require");
if (!lua_isfunction(L, -1)) {
printf("require not found\n");
return 2;
}
lua_pushstring(L, "tool");
if (lua_pcall(L, 1, 1, 0) != LUA_OK) {
printf("require_fail=%s\n", lua_tostring(L, -1));
return 3;
}
lua_getfield(L, -1, "add");
lua_pushinteger(L, 2);
lua_pushinteger(L, 3);
lua_pcall(L, 2, 1, 0);
int n = luaL_checkint(L, -1);
printf("n=%d\n", n);
return 0;
}
I also compile & link with liblua.a, but error occurs when I run it:
"require_fail=multiple Lua VMs detected"
Someone's blog said that in lua5.2, you should link c module and c host program both dynamicly, but not staticly.
is there someone that has the same problem, or is there somehing wrong in my code, thanks.
NOTICE:
the problem has been solved by compile main program with -Wl,-E, thanks a lot for all your help ^^.
Don't link your C module with liblua.a when you create a .so from it. For examples, see my page of Lua libraries: http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/ . You can link liblua.a statically into your main program but you have to export its symbols by adding -Wl,-E at link time. That's how the Lua interpreter is built in Linux.

Resources