VS Code can't find malloc.c - c++

I'm getting an eror when I include cstdlib in C++.
Unable to open 'malloc.c': File not found (file:///build/glibc-bfm8X4/glibc-2.23/malloc/malloc.c).
The error comes from the top part of the VS code window.
(the error occurs during debugging.)
Here's some of the code:
#include <cstdlib>
#include <portaudio.h>
//...
static int paCallback( const void *inputBuffer, void *outputBuffer,
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData )
{
/* Cast data passed through stream to our structure. */
paTestData *data = (paTestData*)userData;
float *out = (float*)outputBuffer;
unsigned int i;
(void) inputBuffer; /* Prevent unused variable warning. */
for( i=0; i<framesPerBuffer; i++ )
{
*out++ = data->left_phase; /* left */
*out++ = data->right_phase; /* right */
float currentSample = 0;
char *sampleData = new char[4];
for(int j = 0; j < 4; j++)
{
sampleData[j] = currentBuffer[&currentIndex + j];
}
currentSample = (float)atof(sampleData); //cstdlib is included to use atof
//gets audio sample data and forwards to PortAudio
data->left_phase = currentSample;
data->right_phase = currentSample;
currentIndex += 4;
}
return 0;
}
I'm using Linux Mint 81.1 if that helps.

I've fixed this in the follow way ..
my error is
"Unable to open 'libc-start.c': File not found (file:///build/glibc-OTsEL5/glibc-2.27/csu/libc-start.c"
so I make a dir in the root directory
$cd /
$sudo mkdir build
$cd build
$sudo mkdir glibc-OTsEL5
$cd glibc-OTsEL5
and then download the glibc from internet
$sudo wget http://ftp.gnu.org/gnu/glibc/glibc-2.27.tar.gz
then unpack it
$sudo tar -xzvf glibc-2.27.tar.gz
every thing seems to be ok
This solution is taken from https://github.com/microsoft/vscode-cpptools/issues/811#issuecomment-406544778

I encounter the same problem. The problem is that I did not compile the cpp file with debug flag -g.........When I re-compile the cpp file containing malloc and reinterpret_cast, the problem disappeared.
But I am wrong. The true solution is not to step the line that malloc is in, other wise, the source file of malloc.c is needed.
cf, https://github.com/microsoft/vscode-cpptools/issues/811#issuecomment-559085447

Related

Am I able to use parallel STL algorithms from C++17/C++20 in Matlab MEX functions?

I am putting together a minimal example leveraging parallelism features in C++17/20 within Matlab MEX functions. I am able to compile and run the mex function from Matlab, but when I set the execution policy of my C++ STL function to "par" instead of "seq", Matlab gives a runtime linkage complaint. Code and error message follows:
test.m (Matlab top-level script):
vec_in = zeros(5);
coeff = 0.05;
vec_out = test_mex_gateway(vec_in, coeff);
test_mex_gateway.cpp (C++ interface to Matlab):
#include "mex.h"
extern void test_execute(float *array_in, float *array_out, const size_t vec_size, const float coeff);
void mexFunction( int nlhs,
mxArray *plhs[],
int nrhs,
const mxArray *prhs[] )
{
// Check for proper number of input and output arguments
if( nrhs != 2 )
{
mexErrMsgTxt( "3 input arguments required: input_data, coeff" );
}
if( nlhs > 2 )
{
mexErrMsgTxt( "Too many output arguments." );
}
const mwSize *matlab_data_dims_in;
mwSize matlab_data_dims_out[1];
// Input Parameters
float *input_data = (float *) mxGetData(prhs[0]);
float coeff = mxGetScalar(prhs[1]);
// Get dimensions
matlab_data_dims_in = mxGetDimensions(prhs[0]);
const int vec_len = matlab_data_dims_in[1];
// Set output data dimension
matlab_data_dims_out[0] = vec_len;
// Output data
plhs[0] = mxCreateNumericArray(1, matlab_data_dims_out, mxSINGLE_CLASS, mxREAL);
float *output_data = (float *) mxGetData(plhs[0]);
test_execute(input_data, output_data, vec_len, coeff);
}
test_execute.cpp (This is where the actual C++ STL call is made):
#include <execution> // std::execution::*
#include <numeric> // std::exclusive_scan()
void test_execute(float *array_in, float *array_out, const size_t vec_size, const float coeff)
{
std::exclusive_scan
(
std::execution::par, // std::execution::seq works here for Mex call, par does not
array_in,
array_in + vec_size,
array_out,
0.0f,
[coeff](float a, float b)
{
float ret = a + b + coeff;
return ret;
}
);
}
I also have a stand-alone main function to replace the Mex wrapper to do a pure C++ test, test_standalone.cpp:
#include <vector>
#include <iostream>
size_t VEC_NUM_ELEM = 10;
extern void test_execute(float *array_in, float *array_out, const size_t vec_size, const float coeff);
int main(int argc, char **argv)
{
if (argc != 2)
{
std::cout << "Try: " << argv[0] << "<coeff>" << std::endl;
return -1;
}
const float coeff = std::stof(argv[1]);
std::cout << "Coeff: " << coeff << std::endl;
float __attribute__ ((aligned (64))) *vec1_array = (float *)malloc(VEC_NUM_ELEM * sizeof(float));
float __attribute__ ((aligned (64))) *vec2_array = (float *)malloc(VEC_NUM_ELEM * sizeof(float));
for (unsigned i = 0; i < VEC_NUM_ELEM; i++)
{
vec1_array[i] = static_cast<float>(i);
}
test_execute(vec1_array, vec2_array, VEC_NUM_ELEM, coeff);
return 0;
}
Here is how I am building and linking, build.sh:
#!/bin/bash
rm *.o
rm *.exe
rm *.mexa64
cstd=c++17
gpp910=/home/m/compilers/bin/g++
tbblib=/home/m/reqs/tbb/lib/intel64/gcc4.8
echo "Building test_execute.cpp..."
$gpp910 -std=$cstd -I/home/m/reqs/tbb/include -L$tbblib -ltbb -Wl,rpath=$tbblib -c test_execute.cpp -fPIC
echo "Building test_standalone.cpp..."
$gpp910 -std=$cstd -L$tbblib test_execute.o test_standalone.cpp -o test_standalone.exe -ltbb
echo "Building test_mex_gateway.cpp..."
mex test_execute.o test_mex_gateway.cpp -L$tbblib -ltbb
The parallel STL calls has a requirement to link against the Intel TBB (Threading Building Blocks), so before I run Matlab to call test.m OR before I run my test_standalone.exe, I run:
export LD_LIBRARY_PATH=/home/m/reqs/tbb/lib/intel64/gcc4.8:$LD_LIBRARY_PATH
I also make sure to make the the C++ library associated with the version of GCC we built with available at runtime:
export LD_LIBRARY_PATH=/home/m/compilers/lib64:$LD_LIBRARY_PATH
When I run test_standalone.exe, everything behaves normally whether I have the execution policy set to "par" or "seq" on std::exclusive_scan. When run test.m, if "seq" was compiled, I can run with no errors. If "par" was compiled, Matlab complains at runtime about a linkage issue:
Invalid MEX-file 'test_mex_gateway.mexa64': test_mex_gateway.mexa64: undefined symbol:
_ZN3tbb10interface78internal20isolate_within_arenaERNS1_13delegate_baseEl
I suspect this was a function that was supposed to be linked from TBB, which I confirmed:
$ nm /home/m/reqs/tbb/lib/intel64/gcc4.8/libtbb.so.2 | grep baseEl
0000000000028a30 T _ZN3tbb10interface78internal20isolate_within_arenaERNS1_13delegate_baseEl
000000000005ed70 r _ZN3tbb10interface78internal20isolate_within_arenaERNS1_13delegate_baseEl$$LSDA
I confirmed Matlab's LD_LIBRARY_PATH has the path I supplied in the above "export .." to this library.
I tried making sure my libraries came before the many Matlab-centric paths Matlab adds to LD_LIBRARY_PATH after it launches from the terminal.
I tried baking the path to the linked libraries via a -Wl,rpath=<path_to_tbb.so> passage to the linker.
After almost two days, I can't figure out why Matlab is having this very specific runtime issue, especially when the pure C++ version is not. Any help would be appreciated.
RHEL 7.9
Matlab R2020a
GCC 9.1.0
TBB (Intel Thread Building Blocks) 2020.3
It appears that Matlab comes with a version of libtbb.so included in its installation. From what I can tell, when launching a Mex file, Matlab will use its own libraries first, regardless of your LD_LIBRARY_PATH order. This is what was giving me runtime issues as a Mex file but not as a pure C++ file. Removing the libtbb.so from Matlab's installation directory allowed runtime linkage to find my version of libtbb, and I was able to run without errors. Thanks to Cris Luengo for pointing me in the right direction.

Nsight CUDA linkage problem between multiple .cu, .h and .c files

This is the first time I am trying to build my CUDA app in NSight Ubuntu to benefit from optimization and profiling. This app works fine from terminal using nvcc (makefile) in Ubuntu 20 (or 18 ,16). I have multiple .cu, .c and .h files. All the files are first included in a flags.h file. My code starts with main.cu (has a main() function) file and this file has # include "flags.h" to make sure all the files are included to compile the code.
flags.h has a lot of #define as well to be later used in different .cu and .c files.
However, inside NSight, none of the #define parameters defined in flags.h are recognized in any of the files and I am getting error.
Following is screenshot of error .
I am attaching a simple square_array problem split in 3 files (main.cu, flags.h and square_.cu).
I can not build this in NSight. Can someone try to build it and let me know please.
Any help or suggestion will be much appreciated.
main.cu
#include <stdio.h>
#include <stdlib.h>
#include "flags.h"
int main(void) {
int i;
int *a_h, *a_d;
CUDA_CHECK_RETURN(cudaMalloc((void**) &a_d, sizeof(int) * WORK_SIZE));
a_h = (int *)malloc(sizeof(int) * WORK_SIZE); // Allocate array on host
for (i = 0; i < WORK_SIZE; i++)
a_h[i] = i+2.;
int block_size = 4;
int n_blocks = WORK_SIZE/block_size + (WORK_SIZE%block_size == 0 ? 0:1);
sq_array<<<n_blocks, block_size>>>(a_d);
CUDA_CHECK_RETURN(cudaGetLastError());
CUDA_CHECK_RETURN(cudaMemcpy(a_h, a_d, sizeof(int) * WORK_SIZE, cudaMemcpyDeviceToHost));
for (i = 0; i < WORK_SIZE; i++)
printf("Input value: %d \n", a_h[i] );
CUDA_CHECK_RETURN(cudaFree((void*) a_d));
CUDA_CHECK_RETURN(cudaDeviceReset());
return 0;
}
flags.h
#ifndef FLAGS_H_
#define FLAGS_H_
#include "square_.cu"
#define CUDA_CHECK_RETURN(value) { \
cudaError_t _m_cudaStat = value; \
if (_m_cudaStat != cudaSuccess) { \
fprintf(stderr, "Error %s at line %d in file %s\n", \
cudaGetErrorString(_m_cudaStat), __LINE__, __FILE__); \
exit(1); \
} }
#define WORK_SIZE 29
#endif /* FLAGS_H_ */
square_.cu
__global__ void sq_array( int *a) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx< WORK_SIZE) a[idx] = a[idx] * a[idx];
}
The problem is the your IDE is compiling square_.cu and compiling main.cu which is also compiling square_.cu again due to the #include "square_.cu" in flags.h which gives you two definitions of sq_array. When square_.cu is compiled the WORK_SIZE macro is not defined giving you a compile time error. When you compiled on the command line you did not compile square_.cu so you avoided this error.
In any case, it is a bad idea to #include .cu (or .c files). These should be compiled separately and then linked together.
You have to organize things differently.
I don't know the details of your code, but you can do something like this:
square.cu:
#include "square.h"
__global__ void sq_array( int *a) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx< WORK_SIZE) a[idx] = a[idx] * a[idx];
}
void host_sq_array(int *a_d) {
int block_size = 4;
int n_blocks = WORK_SIZE/block_size + (WORK_SIZE%block_size == 0 ? 0:1);
sq_array<<<n_blocks, block_size>>>(a_d);
}
square.h:
#ifndef SQUARE_H
#define SQUARE_H
#include "flags.h" // REMOVE #include of .cu file!!!
void host_sq_array(int *a_d);
#endif
You can safely #include square.h which only includes constant, type definitions, and function prototypes.

Issues trying to build a random project in Visual Studio

I am trying to build this project, which is basically an extractor for specific .rom files. As someone with close to zero experience in coding, I am having one issue after another trying to build it.
The project description says it requires zlibstat.lib from zlib in order to build it, so I got the latest zlib, opened it on VS2019, followed these instructions, and built everything, included the required zlibstat.lib.
After opening the project's sln and figuring where to put the zlib related files, I tried to build but it gave me this error in fs.obj: "LNK2019: unresolved external symbol _uncompress referenced in function "int __cdecl run_extract(char *)" (?run_extract##YAHPAD#Z)". This is how far google and my two brain cells has led me to.
I am not exactly sure what I should do to solve this but apparently is has something to do with the run_extract function:
fs.h
#pragma once
#include <iostream>
#include <fstream>
#include "defs.h"
#include <zlib.h>
#pragma comment(lib, "zlibstat.lib")
#include <shlwapi.h>
#pragma comment(lib,"shlwapi.lib")
int run_extract(char *);
and fs.cpp
int run_extract(char *path)
{
std::fstream test;
test.open(path, std::ios::in | std::ios::binary);
if (!test) return -1;
size_t file_size;
test.seekg(0, std::ios::end);
file_size = test.tellg();
test.seekg(0, std::ios::beg);
unsigned char *buffer = new unsigned char [file_size];
test.read((char*)buffer, file_size);
test.close();
jrm_rom_header *ptrHeader = (jrm_rom_header*)buffer;
unsigned long indexLen = ptrHeader->count_index * sizeof(jrm_rom_file_index);
unsigned char *index = new unsigned char [indexLen];
uncompress(index, &indexLen, (const Bytef*)(buffer + ptrHeader->pos_index), ptrHeader->size_index); // use zlib
jrm_rom_file_index *ptrIndex = (jrm_rom_file_index*)index;
unsigned char key = 0;
char *path_out = new char[0x100];
unsigned long ypos = 0, x = 0;
for (x = 0; x<ptrHeader->count_index; x++)
{
key = (ptrIndex->key & 0xff) ^ (ptrIndex->key >> 8 & 0xff) ^ (ptrIndex->key >> 16 & 0xff) ^ (ptrIndex->key >> 24 & 0xff);
get_file_path(path_out, ptrIndex->file_path);
// printf("%04d: file_name = %s\n file_start = 0x%08x, file_size = 0x%08x, key = 0x%02x\n", x, path_out, ptrIndex->pos_start, ptrIndex->size_file, key);
printf("%s: %d bytes.\n", path_out, ptrIndex->size_file);
for (ypos = 0; ypos < ptrIndex->pos_delta; ypos++)
buffer[ypos + ptrIndex->pos_start] ^= key;
try_create_directory(path_out);
test.open(path_out, std::ios::binary | std::ios::out);
test.write((char*)buffer + ptrIndex->pos_start, ptrIndex->pos_delta);
test.close();
ptrIndex++;
}
delete[]path_out;
delete[]index;
delete[]buffer;
return 0;
}
I thought the problems would go away if I used the same Visual Studio version the project was made, so I installed the Visual C++ 2008 and an older version of zlib, only to end up having the exact same error.
Sorry if I am being dumb and having this entire situation poorly written.

How do I get correct file names from readdir on OSX?

I'm trying to get my old filemanager program that I coded years ago with ncurses as a school project to run (the code is not great, might be a good exercise for some refactoring). I created it on Ubuntu, doesn't work on my Macbook. Can't figure out the difference that makes it work on one system, but not the other.
Works fine on Linux:
https://imageshack.com/a/img922/8487/1Atzsx.jpg
But OSX does not display the file names correctly: https://imageshack.com/a/img923/3640/CeRzCm.png
Neither do the type descriptions which are hardcoded based on the d_type from readdir.
At first I thought that there might be an issue with wide character support from ncurses. This should be supported by default on OSX, but to be sure I installed the lastest ncurses from Homebrew. Didn't help.
The file names are obtained in this way and saved into objects:
struct dirent *ent;
DIR *dir;
if((dir = opendir(path.c_str())) != NULL) {
for(auto it = m_files.begin(); it != m_files.end(); ++it) {
delete *it;
}
m_files.clear();
while((ent = readdir (dir)) != NULL) {
if(ent->d_type==DT_DIR) {
if(!root) {
m_files.push_back( new CDirectory(ent->d_name, path+"/"+ent->d_name) );
}else{
m_files.push_back( new CDirectory(ent->d_name, path+ent->d_name) );
}
}
These objects are then accessed to create items for the ncurses menu. Valgrind detects memory leaks here (not happening with the same code on Ubuntu).
void CSelection::CreateItems () {
size_t number_of_choices = m_files.size();
size_t i;
m_items = (ITEM **)calloc(number_of_choices+1, sizeof(ITEM *));
for(i = 0; i < number_of_choices; i++) {
m_items[i] = new_item(m_files[i]->GetName().c_str(), m_files[i]->GetType().c_str());
}
m_items[i] = NULL;
}
After some research I think that I have the same problem as here: https://github.com/rust-lang/libc/issues/414
, but I'm stuck on implementing the fix.
I tried including this code (found here: https://forums.coronalabs.com/topic/53249-link-errors-with-openssl-plugin-when-building-universal-32-64-bit-binaries-for-ios/),
#include <dirent.h>
#include <fnmatch.h>
extern "C" DIR * opendir$INODE64( char * dirName );
DIR * opendir$INODE64( char * dirName )
{
return opendir( dirName );
}
extern "C" struct dirent * readdir$INODE64( DIR * dir );
struct dirent * readdir$INODE64( DIR * dir )
{
return readdir( dir );
}
but I get a segmentation fault on those returns.
Any advice? Thanks in advance.

Using c++ libgpiod library, how can I set gpio lines to be outputs and manipulate single lines with set_value() function?

I just started using c++ bindings of libgpiod library and have problem with settings gpios. I know, that I can create long vector of values, and apply it in all at once, but I would like to be able to set their direction, and control them separately. How can I do that?
What I tried is this:
First: Working code with applying all values at once:
#include <gpiod.hpp>
int main(int argc, char **argv)
{
::gpiod::chip chip("gpiochip0");
auto lines = chip.get_all_lines();
::gpiod::line_request requestOutputs = {
argv[0],
::gpiod::line_request::DIRECTION_OUTPUT,
0
};
int value_to_be_set = 0xAAAAAAA ; //example value
::std::vector<int> values;
for (int i = 0; i < 32; i++)
{
values.push_back((value_to_be_set >> i) & 1UL);
}
lines.request(requestOutputs, values);
lines.release();
return EXIT_SUCCESS;
}
Second, my approach to do that I want:
#include <gpiod.hpp>
int main(int argc, char **argv)
{
::gpiod::chip chip("gpiochip0");
auto lines = chip.get_all_lines();
::gpiod::line_request requestOutputs = {
argv[0],
::gpiod::line_request::DIRECTION_OUTPUT,
0
};
lines.request(requestOutputs);
int value_to_be_set = 0xAAAAAAA; //example value
for (int i = 0; i < 32; i++)
{
// This does not set value :(
lines.get(i).set_value((value_to_be_set >> i) & 1UL);
}
lines.release();
return EXIT_SUCCESS;
}
I also could not find a simple C++ example to toggle a single GPIO line using the latest Raspberry PI libraries.
There is a multi-line example below but this is not what was originally asked:
https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/tree/bindings/cxx
Below is an example that will cause GPIO17 to go high then low to create a single line output pulse.
// Use gpio drivers to toggle a single GPIO
// line on Raspberry Pi
// Use following commands to install prerequisites and build
// sudo apt install gpiod
// sudo apt install libgpiod-dev
// g++ -Wall -o gpio gpip.cpp -lgpiodcxx
#include <iostream>
#include <gpiod.hpp>
#include <unistd.h>
int main(void)
{
::gpiod::chip chip("gpiochip0");
auto line = chip.get_line(17); // GPIO17
line.request({"example", gpiod::line_request::DIRECTION_OUTPUT, 0},1);
sleep(0.1);
line.set_value(0);
line.release();
}
also don't forget to build with the flag -lgpiodcxx (for c++) or -lgpiod (for c)