#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[]) {
printf("Write in this format: <operand1> <operator> <operand2>\n");
double result, op1, op2;
op1 = atof(argv[1]);
op2 = atof(argv[3]);
if(argv[2][0]=='+')
result = op1 + op2;
if(argv[2][0]=='-')
result = op1 - op2;
if(argv[2][0]=='/')
result = op1 / op2;
if(argv[2][0]=='x')
result = op1 * op2;
printf("Result: %f", result);
return 0;
}
I'm trying to make this work but it's causing a Segmentation fault. I've checked my code and I just can't find anything wrong with it. It's supposed to work like a simple calculator. And then I tried the man page for argv or argc and it says, "No manual entry for..." something like that. I mean, isn't there supposed to be one? Or do I have to update something?
I'd appreciate it if anyone would reply whatever he/she think/s that can help. Thanks in advance!
Your code have a syntaxis/concept error in the four conditionals.
You are requesting argv[2][0] but it should be argv[2] instead:
argv[2][0] means: the position cero of a pointer to char (bad) in the third position in the array
argv[2] means: the content of the pointer to char that is in the third position in the array
That is why you get the Segmentation fault error.
Related
I have code that runs with FreeRTOS and I want to edit it,
its a code that measure the pressure and the temperature, and I want to have the time when these measures are token.
Could anyone tell me how to get the current time in my machine or the date?
Thank you.
This is the code that I am using right now.
//#include <stdio.h>
//#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include "platform.h"
#include "printf.h"
#include "lps331ap.h"
static void app_task(void *);
int main(int argc, char *argv[])
{
// Initialize the platform
platform_init();
// Create a task for the application
xTaskCreate(app_task, (const signed char * const) "lps331", configMINIMAL_STACK_SIZE, NULL, 1, NULL);
// Run
platform_run();
return 0;
}
static void app_task(void *param)
{
uint32_t pres;
int16_t temp;
int count=0;
// FILE* fichier = NULL;
printf("# Testing LPS331AP\n");
printf("# Initializing LPS331AP...\n");
lps331ap_powerdown();
printf("# Setting LPS331AP pressure sensor\n");
lps331ap_set_datarate(LPS331AP_P_12_5HZ_T_12_5HZ);
while (1)
{
lps331ap_read_pres(&pres);
lps331ap_read_temp(&temp);
//fichier = fopen("test.txt", "w");
//fprintf(fichier,"%f", pres / 4096.0);
//fprintf(fichier,"%f", 42.5 + temp / 480.0 );
printf("%d\t",count);
printf("%f\t", 42.5 + temp / 480.0);
printf("%f\n", pres / 4096.0);
count=count+1;
//fclose(fichier);
//vTaskDelay(configTICK_RATE_HZ / 10);
vTaskDelay(2000);
//vTaskDelay(600000);
}
}
For measuring time, there's xTaskGetTickCount, but this will be limited to the resolution of your tick rate.
Alternatively, you can create another task that ticks at 1 Hz to increment a counter and use that as system time.
To get an actual date however, you'll need to consult your development board and see if it has an RTC. Otherwise, you'll need to get the time manually somehow and maintain this count using your development board's hardware timers.
There's bound to be some hardware clocks in your development board that you can use to measure time as well.
In order to create a MEX function and use it in my MATLAB code, like this:
[pow,index] = mx_minimum_power(A11,A12,A13,A22,A23,A33);
I've created the file mx_minimum_power.cpp and written the following code in it:
#include <math.h>
#include <complex>
#include "mex.h"
#include "matrix.h"
#include "cvm.h"
#include "blas.h"
#include "cfun.h"
using std::complex;
using namespace cvm;
/* The gateway function */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
const int arraysize = 62172;
const int matrixDimention = 3;
float *inMatrixA11 = (float *)mxGetPr(prhs[0]);
complex<float> *inMatrixA12 = (complex<float> *)mxGetPr(prhs[1]);
complex<float> *inMatrixA13 = (complex<float> *)mxGetPr(prhs[2]);
float *inMatrixA22 = (float *)mxGetPr(prhs[3]);
complex<float> *inMatrixA23 = (complex<float> *)mxGetPr(prhs[4]);
float *inMatrixA33 = (float *)mxGetPr(prhs[5]);
basic_schmatrix< float, complex<float> > A(matrixDimention);
int i = 0;
for (i = 0; i < arraysize; i++)
{
A.set(1, 1, inMatrixA11[i]);
A.set(1, 2, inMatrixA12[i]);
A.set(1, 3, inMatrixA13[i]);
A.set(2, 2, inMatrixA22[i]);
A.set(2, 3, inMatrixA23[i]);
A.set(3, 3, inMatrixA33[i]);
}
}
And then in order to be able to debug the code, I've created the mx_minimum_power.pdb and mx_minimum_power.mexw64 files, using the following code in the Matlab Command Window:
mex -g mx_minimum_power.cpp cvm_em64t_debug.lib
The files blas.h, cfun.h, cvm.h and cvm_em64t_debug.lib are in the same directory as mx_minimum_power.cpp.
They are the headers and library files of the CVM Class Library.
Then I've attached MATLAB.exe to Visual Studio 2013, using the way explained here.
and have set a breakpoint at line40:
When I run my MATLAB code, there's no error until the specified line.
But if I click on the Step Over button, I'll encounter the following message:
With the following information added to the Output:
First-chance exception at 0x000007FEFCAE9E5D in MATLAB.exe: Microsoft C++ exception: cvm::cvmexception at memory location 0x0000000004022570.
> throw_segv_longjmp_seh_filter()
throw_segv_longjmp_seh_filter(): C++ exception
< throw_segv_longjmp_seh_filter() = EXCEPTION_CONTINUE_SEARCH
Can you suggest me why libmex.pdb is needed at that line and how should I solve the issue?
If I stop debugging, I'll get the following information in MATLAB Command Window:
Unexpected Standard exception from MEX file.
What() is:First index value 0 is out of [1,4) range
Right before pressing the step over button, we have the following values for A11[0],A12[0],A13[0],A22[0],A23[0],A33[0]:
that are just right as my expectations, according to what MATLAB passes to the MEX function:
Maybe the problem is because of wrong allocation for matrix A, it is as follows just before pressing the step over button.
The problem occurs because we have the following code in lines 48 to 53 of the cvm.h file:
// 5.7 0-based indexing
#if defined (CVM_ZERO_BASED)
# define CVM0 TINT_ZERO //!< Index base, 1 by default or 0 when \c CVM_ZERO_BASED is defined
#else
# define CVM0 TINT_ONE //!< Index base, 1 by default or 0 when \c CVM_ZERO_BASED is defined
#endif
That makes CVM0 = 1 by default. So if we press the Step Into(F11) button at the specified line two times, we will get into line 34883 of the file cvm.h:
basic_schmatrix& set(tint nRow, tint nCol, TC c) throw(cvmexception)
{
this->_set_at(nRow - CVM0, nCol - CVM0, c);
return *this;
}
Press Step Into(F11) at line this->_set_at(nRow - CVM0, nCol - CVM0, c); and you'll go to the definition of the function _set_at:
// sets both elements to keep matrix hermitian, checks ranges
// zero based
void _set_at(tint nRow, tint nCol, TC val) throw(cvmexception)
{
_check_lt_ge(CVM_OUTOFRANGE_LTGE1, nRow, CVM0, this->msize() + CVM0);
_check_lt_ge(CVM_OUTOFRANGE_LTGE2, nCol, CVM0, this->nsize() + CVM0);
if (nRow == nCol && _abs(val.imag()) > basic_cvmMachMin<TR>()) { // only reals on main diagonal
throw cvmexception(CVM_BREAKS_HERMITIANITY, "real number");
}
this->get()[this->ld() * nCol + nRow] = val;
if (nRow != nCol) {
this->get()[this->ld() * nRow + nCol] = _conjugate(val);
}
}
pressing Step Over(F10) button,you'll get the result:
so in order to get nRow=1 and nCol=1 and not nRow=0 and nCol=0, which is out of the range [1,4), you should write that line of code as:
A.set(2, 2, inMatrixA11[i]);
Thanks first for your time spent here. I have a question with snprintf() when size=0, with code below:
#include <stdio.h>
#include <stdlib.h>
int main(int ac, char **av)
{
char *str;
int len;
len = snprintf(NULL, 0, "%s %d", *av, ac);
printf("this string has length %d\n", len);
if (!(str = malloc((len + 1) * sizeof(char))))
return EXIT_FAILURE;
len = snprintf(str, len + 1, "%s %d", *av, ac);
printf("%s %d\n", str, len);
free(str);
return EXIT_SUCCESS;
}
when I run:
momo#xue5:~/TestCode$ ./Test_snprintf
The result is:
this string has length 17
./Test_snprintf 1 17
What confuses me is in the code, the size to be written is 0, why displayed 17?
What did I miss?
Thanks~~
The solution can be found in the man page under Return value;
The functions snprintf() and vsnprintf() do not write more than size bytes (including the terminating null byte ('\0')). If the output was truncated due to this limit then the return value is the number of characters (excluding the terminating null byte) which would have been written to the final string if enough space had been available.
This is so that you can do exactly what you do, a "trial print" to get the correct length, then allocate the buffer dynamically to get the whole output when you snprintf again to the allocated buffer.
I got the following error when I ran a c++ function in Matlab.
WARNING: Couldn't read movie file example.avi
Unexpected Standard exception from MEX file.
What()
is:/tmp/A3p1_2964_800/batserve/A3p1/maci64/OpenCV/modules/imgproc/src/color.cpp:3256:
error: (-215) scn == 3 || scn == 4 in function cvtColor
..
Error in rundemo (line 2)
r = facedetection(inputVideo);
Below is the code for facedetection.cpp
#include <iostream>
#include <vector>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include "mex.h"
using namespace std;
using namespace cv;
vector<Rect> detect(Mat img, CascadeClassifier face_cascade){
vector<Rect> faces;
Mat img_gray;
cvtColor(img, img_gray, COLOR_BGR2GRAY);
face_cascade.detectMultiScale(img_gray, faces, 1.1, 2);
return faces;
}
void mexFunction(int nlhs, mxArray *plhs[ ],int nrhs, const mxArray *prhs[ ]){
VideoCapture inputVideo(mxArrayToString(prhs[0]));
Mat img;
inputVideo >> img;
string face_cascade_name = "/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml";
CascadeClassifier face_cascade;
face_cascade.load(face_cascade_name);
vector<Rect> rects = detect(img,face_cascade);
int numFaces = rects.size();
plhs[0] = (mxArray *) mxCreateNumericMatrix(numFaces,4,mxDOUBLE_CLASS,mxREAL);
double* outPtr = mxGetPr(plhs[0]);
for(int i = 0; i < numFaces; i++){
Rect rect = rects[i];
outPtr[i+0*numFaces] = rect.x;
outPtr[i+1*numFaces] = rect.y;
outPtr[i+2*numFaces] = rect.width;
outPtr[i+3*numFaces] = rect.height;
}
}
I guess there is something wrong in the path I assigned to the face_cascade_name. This code rans on a Windows computer with a different path, and then I changed it to the one shown because I use a Mac. This is the path to haarcascade_frontalface_alt.xml on my computer. Thank you for helping!
First, check that your video is being read in properly. You said the code works on windows. Make sure that your path to the video is correct.
In your mex function, add
Mat img;
inputVideo >> img;
// Add the following lines to check if img is valid
if (img.data == NULL)
{
printf("Video not read in properly\n");
exit(1);
}
Next, check the number of channels for img. If you run cvtColor(img, COLOR_BGR2GRAY), you need the number of channels to be 3.
printf("Number of channels for img: %d\n", img.channels());
If the number of channels is equal to 1, then your img is already single channel, which is why cvtColor is giving an error. So no color conversion is necessary in this case and you can just comment out the line for cvtColor and the error should be gone.
As a side note, to debug this, you might want to display a couple of frames of the video, i.e., display img for a few frames just to check that they look right.
I am new to OpenMP. I have the following code which compiles fine using Matlab mex configured with MSVS2010. The computer has 8 processors available (which I checked also by using matlabpool).
#include "mex.h"
#include <omp.h>
typedef unsigned char uchar;
typedef unsigned int uint;
//Takes a uint8 input array and uint32 index array and preallocated uint8 array the same
//size as the first one and copies the data over using the indexed mapping
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] )
{
uint N = mxGetN(prhs[0]);
mexPrintf("n=%i\n", N); mexEvalString("drawnow");
uchar *input = (uchar*)mxGetData(prhs[0]);
uint *index = (uint*)mxGetData(prhs[1]);
uchar *output = (uchar*)mxGetData(prhs[2]);
uint nThreads, tid;
#pragma omp parallel private(tid) shared(input, index, output, N, nThreads) num_threads(8)
{
tid = omp_get_thread_num();
if (tid==0) {
nThreads = omp_get_num_threads();
}
for (int i=tid*N/nThreads;i<tid*N/nThreads+N/nThreads;i++){
output[i]=input[index[i]];
}
}
mexPrintf("nThreads = %i\n",nThreads);mexEvalString("drawnow");
}
The output I get is
n=600000000
nThreads = 1
Why is only one thread being created despite me requesting 8?
Sigh. Typical, spend hours trying and failing and then find the answer 5 minutes after posting to SO.
The file needs to be mexed with openmp support
mex mexIndexedCopy.cpp COMPFLAGS="/openmp $COMPFLAGS"