Unexpected output from lex program - lex

I have written a simple lex program to perform average of positive numbers , the program is compiling fine but i'm not able to get the expected output.I'm passing the input to the program from a file by giving filename as a commandline argument.The output of the lex program is blank showing no result , i'm a beginner in lex and any help would be appreciated . I have attached the code below. The code is written in redhat linux kernel version 2.4.
%{
#include <stdio.h>
#include <stdlib.h>
%}
%%
[0-9]+ return atoi(yytext);
%%
void main()
{
int val, total = 0, n = 0;
while ( (val = yylex()) > 0 ) {
total += val;
n++;
}
if (n > 0) printf(“ave = %d\n”, total/n);
}
The input file contains numbers 3,6 and 4 and the name of the file is passed as command line argument.
./a.out < input

Your program works for me. I'm a bit suspicious of yywrap missing, so you probably link with the -lfl (or something alike) option. This library contains a yywrap and a main. Even though I'm not able to reproduce what you see, I'm wary that maybe the main from libfl is used. I'm assuming you do get any newlines in the input file on the output. Different linkers have different ways of resolving multiple occurrences of the same symbol.
All in all I think you have to look for the problem in the way your program is built, because the specification seems ok. If you add int yywrap(void) { return 1; } after your main, then you can do without libfl, which is what I would advise any user of lex and gnu-flex.

Related

Can't compile an example program from The C Programming Language

I know programming in Java, but I'm reading "The C Programming Language", second edition. It says that to compile and run a program from the command line you have to do:
$ cc hello.c //assuming the name of the file is hello.c
./a.out
and hello world is printed. I tried that and worked fine.
Now, there is another example that prints a bunch of Celsius and Fahrenheit temperatures, so I created a file called TemperatureConverter.c with the given code. However, in the command line, when I ran:
$ cc TemperatureConverter.c
I got an error:
/usr/lib/gcc/x86_64-redhat-linux/4.8.3/../../../../lib64/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
I don't know what this means. I tried double checking my syntax and it looks correct. I included the screenshot of the given code compared to the code I wrote, in case anybody notices a difference that may be causing the error:
#include <stdio.h>
main()
{
float fahr, celcius;
int lower, upper, step;
lower = 0;
upper = 300;
step = 20;
fahr = lower;
while (fahr <= upper) {
celcius = (5.0/9.0) * (fahr - 32.0);
printf("%3.0f %6.1f\n", fahr, celcius);
fahr = fahr + step;
}
}
I just ran your code in cygwin using the same command and it compiled/ran fine. I will say the same things others have mentioned.
main has the return type int.
it's parameters should be (void) or (int argc, **int argv).
You can have main() however this lets any parameters be passed into the main function.
Third the main function should end with return 0;
This indicates that the program exited correctly.
In the end it should look like this
#include <stdio.h>
int main(void)
{
float fahr, celcius;
int lower, upper, step;
lower = 0;
upper = 300;
step = 20;
fahr = lower;
while (fahr <= upper) {
celcius = (5.0/9.0) * (fahr - 32.0);
printf("%3.0f %6.1f\n", fahr, celcius);
fahr = fahr + step;
}
return 0;
}
There's absolutely nothing syntacticly wrong with your code. Though the modifications suggested by FrozenHawk are a good idea. I noticed the linker error talks about an undefined reference to main in function _start. I've never even heard of a function _start as the starting point in a c file; though that could be an internal, compiler specific, thing not strictly specified in the standards.
You should be absolutely sure you're trying to compile the correct file. Use cat on the same argument for extra assurance. Your code compiled just fine for me, as is, and with the commands you used on Debian. It seems unlikely, but this could be an issue with gcc. On my machine, no function called _start appears in any files in /usr/include/, which implies something lower level. You might consider uninstalling and reinstalling as a last resort.

Deploy an matlab file to executable

I want to deploy an m file into an executable. I am using mcc command: mcc -m epidemic.m. Epidemic is my function which takes no arguments and returns a vector and write that vector to txt. Mcc creates epidemic.exe and when I am running that exe it creates the txt file however it seems that it doesnt return values (the return value of .exe). I am trying to run the exe from matlab using:
cmd = ['epidemic.exe '];
system(cmd);
It return cmdout " and status 0. How can I take the returned values of the .exe?
When you compile matlab code like:
function [out1, out2] = epidemic(in1, in2, in3)
%[
...
%]
to standalone (mcc -m epidemeic.m), Matlab produces somehow the following pseudo c-code and compiles it to .exe:
int main(int argc, char** argv)
{
// Load compiled code produced by mcc
HMCRInstance* hInst = loadByteCodeProducedByMccFromResources();
// Similar to have wrote in matlab "epidemic(argv[0], argv[1], ...)"
// 1) Without asking for any argument output
// 2) Argument inputs are passed as strings
int errorCode = mclFevalFromExeArg(hInst, "epidemic", argc, argv);
return errorCode; // only indicates if call to 'mclFEvalFromExeArg'
// succeded, it does not relate to out1, out2 at all.
}
NB: If you want to see the exact code produced by mcc, use mcc -W main -T codegen epidemic.m
So, directly compiling to standalone, you cannot work with outputs of your Matlab function. If you need to play around with output arguments of epidemic, either
[Simple solution] Consider saving outputs to files or display them to shell console using disp (NB: you can use isdeployed in your .m file to check if you're running from matlab or from compiled code).
[Advanced solution] Consider compiling your code to shared library (mcc -l epidemic.m) instead of standalone (mcc -m epidemeic.m)
NB: When you compile your code to shared library, mcc will produce a dll that exports the following function:
extern LIB_epidemeic_C_API
bool MW_CALL_CONV mlxEpidemic(int nlhs, mxArray *plhs[], int nrhs, mxArray *prhs[]);
nrhs/prhs are the number of input arguments and their values (as mxArray type). And nlhs/plhs are the ouput arguments you want to have when calling epidemic. Up to you to do the marshaling between mxArray and equivalent C native type.
EDIT
As you indicate that epidemic returns a vector of values, you can display them from standalone like this:
function [output] = epidemic(v1, v2, v3)
%[
% When called from system cmd line, v1, v2, v3 are passed
% as string. Here is how to convert them to expected type if required
if (ischar(v1)), v1 = str2double(v1); end
if (ischar(v2), v2 = str2double(v2); end
if (ischar(v3)), v3 = str2double(v3); end
...
output = ...;
...
if (isdeployed())
disp(output);
end
%]
An exe does not have a return value, you need to find another way to transport the data back, for example via console outputs or text files. What you get is the error code and error message.

How to save a svm file in mexopencv

So, I am about to train a classifier and needed to save the result from the classifier, in mexopencv.
hello = cv.SVM;
hello.save('foo.xml')
My Matlab compiler crashes due to segmentation fault. As far as I know this is supposed to be the way in OpenCV. Is there any other way to save files trained via SVM in mexopencv ; or is this something to do with Matlab file writing option. Thanks.
This is in fact a bug in OpenCV itself, not mexopencv. You should report it...
Here is a minimal C++ program to reproduce the bug:
#include "opencv2/opencv.hpp"
#include "opencv2/ml/ml.hpp"
using namespace cv;
int main()
{
Ptr<SVM> svm = new SVM();
svm->save("svm.xml");
return 0;
}
Running this under a debugger, I located the offending code:
df_count = class_count > 1 ? class_count*(class_count-1)/2 : 1;
df = decision_func;
cvStartWriteStruct( fs, "decision_functions", CV_NODE_SEQ );
for( i = 0; i < df_count; i++ )
{
int sv_count = df[i].sv_count;
...
}
At this point, the SVM model is untrained, and df is an uninitialized pointer. class_count equals 0, but df_count gets set to 1, hence df[i] (with i=0) causes an access violation...
I think this could be fixed as:
df_count = class_count > 1 ? class_count*(class_count-1)/2 : 1;
if (class_count == 0) df_count = 0;
Changing df_count to 0 during debugging, the program runs correctly and I get the following XML file:
svm.xml
<?xml version="1.0"?>
<opencv_storage>
<my_svm type_id="opencv-ml-svm">
<svm_type>C_SVC</svm_type>
<kernel>
<type>RBF</type>
<gamma>1.</gamma>
</kernel>
<C>1.</C>
<term_criteria>
<epsilon>1.1920928955078125e-007</epsilon>
<iterations>1000</iterations>
</term_criteria>
<var_all>0</var_all>
<var_count>0</var_count>
<sv_total>0</sv_total>
<support_vectors></support_vectors>
<decision_functions></decision_functions>
</my_svm>
</opencv_storage>
For now you could avoid the bug by training the model first before saving it to file :)
You can try libsvm which has a Matlab interface. It comes two functions to read and write in svm (libsvmwrite and libsvmread).

Calling mxDestroyArray on mxArray objects returned from Matlab Compiler Runtime

We've been interfacing with a library created from the Matlab Compiler. Our problem is related to an array returned from the library.
Once we're finished with the array, we'd like to free the memory, however, doing this causes occasional segmentation faults.
Here is the Matlab library (bugtest.m)::
function x = bugtest(y)
x = y.^2;
Here is the command we used to build it (creating libbugtest.so, and libbugtest.h)::
mcc -v -W lib:libbugtest -T link:lib bugtest.m
Here is our C test program (bug_destroyarray.c)::
#include <stdio.h>
#include <stdlib.h>
#include "mclmcrrt.h"
#include "libbugtest.h"
#define TESTS 15000
int main(int argc, char **argv)
{
const char *opts[] = {"-nojvm", "-singleCompThread"};
mclInitializeApplication(opts, 2);
libbugtestInitialize();
mxArray *output;
mxArray *input;
double *data;
bool result;
int count;
for (count = 0; count < TESTS; count++) {
input = mxCreateDoubleMatrix(4, 1, mxREAL);
data = mxGetPr(input); data[0] = 0.5; data[1] = 0.2; data[2] = 0.2; data[3] = 0.1;
output = NULL;
result = mlfBugtest(1, &output, input);
if (result) {
/* HERE IS THE PROBLEMATIC LINE */
/*mxDestroyArray(output);*/
}
mxDestroyArray(input);
}
libbugtestTerminate();
mclTerminateApplication();
}
Here is how we compile the C program (creating bug_destroyarray)::
mbuild -v bug_destroyarray.c libbugtest.so
We believe that mxDestroyArray(output) is problematic.
We run the following to test crashing:
On each of the 32 cluster nodes.
Run bug_destroyarray.
Monitor output for segmentation faults.
Roughly 10% of the time there is a crash. If this is independent across nodes
then you might suppose it is crashing roughly 0.3% of the time.
When we take out that problematic line we are unable to cause it to crash.
However memory usage gradually increases when this line is not included.
From the research we've done, it seems we are not supposed to destroy the array returned, if not, how do we stop from leaking memory?
Thanks.
Okay, I know this is a little old now, but in case it helps clarify things for anyone passing by ...
Amro provides the most pertinent information, but to expand upon it, IF you don't call the mxDestroyArray function as things stand, then you WILL leak memory, because you've set output to NULL and so the mlf function won't try to call mxDestroyArray. The corollary of this is that if you've called mxDestroyArray AND then try to call the mlf function AND output is NOT NULL, then the mlf function WILL try to call mxDestroyArray on output. The question then is to what does output point? It's a bit of a dark corner what happens to output after passing it to mxDestroyArray. I'd say it's an unwarranted assumption that it's set to NULL; it's certainly not documented that mxDestroyArray sets its argument to NULL. Therefore, I suspect what is happening is that in between your call to mxDestroyArray and the code re-executing the mlf function, something else has been allocated the memory pointed to by output and so your mlf function tries to free memory belonging to something else. Voila, seg fault. And of course this will only happen if that memory has been reallocated. Sometimes you'll get lucky, sometimes not.
The golden rule is if you're calling mxDestroyArray yourself for something that is going to be re-used, set the pointer to NULL immediately afterwards. You only really need to destroy stuff at the end of your function anyway, because you can safely re-use output variables in mlf calls.
Guy
A few notes:
I don't see singleCompThread in the list of allowed options for mclInitializeApplication.
The recommended way to compile your C program is to dynamically link against the compiled library:
mbuild -v -I. bug_destroyarray.c -L. -lbugtest
At the top of your C program, just include the generated header file, it will include other headers in turn. From looking at the generated header, it has:
#pragma implementation "mclmcrrt.h"
#include "mclmcrrt.h"
I dont know the exact meaning of this pragma line, but maybe it matters with GCC compilers..
The fact that both mlx/mlf generated functions return booleans is undocumented. But looking at the header files, both signatures do indeed return a bool:
extern bool mlxBugtest(int nlhs, mxArray *plhs[], int nrhs, mxArray *prhs[]);
extern bool mlfBugtest(int nargout, mxArray** x, mxArray* y);
I tried your code and it works just fine with no segfaults. As I dont have access to a cluster of computers, my testing was only done on my local machine (WinXP with R2013a).
I had to remove both MCR initialization options for it to work (specifically the nojvm caused a runtime error). Below is the full code with slight modifications. It took around 10 seconds to run:
#include <stdio.h>
#include <stdlib.h>
#include "libbugtest.h"
#define TESTS 15000
int main()
{
mxArray *output, *input;
double *data;
int count;
bool result;
if( !mclInitializeApplication(NULL,0) ) {
fprintf(stderr, "Could not initialize the application.\n");
return EXIT_FAILURE;
}
if ( !libbugtestInitialize() ) {
fprintf(stderr, "Could not initialize the library.\n");
return EXIT_FAILURE;
}
for (count = 0; count < TESTS; count++) {
input = mxCreateDoubleMatrix(4, 1, mxREAL);
data = mxGetPr(input);
data[0] = 0.5; data[1] = 0.2; data[2] = 0.2; data[3] = 0.1;
output = NULL;
result = mlfBugtest(1, &output, input);
if (!result) {
fprintf(stderr, "call failed on count=%d\n", count);
return EXIT_FAILURE;
}
mxDestroyArray(output); output = NULL;
mxDestroyArray(input); input = NULL;
}
libbugtestTerminate();
mclTerminateApplication();
return EXIT_SUCCESS;
}
Also the compilation step is a bit different on Windows, since we statically link against the import lib (which inserts a stub to dynamically load the DLL on runtime):
mbuild -v -I. bug_destroyarray.c libbugtest.lib
Thanks for the detailed reply Amro.
We tried changing our compilation steps to the recommended ones, with no success.
The following fixed our seg-faulting problem:
Do not set output = NULL at each iteration, instead do it once outside of the loop.
Do not call mxDestroyArray(output) inside the loop, reference: here.
Our misunderstanding was that (it seems) you are supposed to reuse mxArray pointers which you pass to MATLAB functions. It makes things slightly cumbersome on our side as we need to be careful reusing this pointer.
However, memory is completely stable, and we've not had a crash since.

Scanf missed line

I wrote a test program which should take in a 3x3 matrix of characters and output the entered matrix. However, I have to enter 4 lines in order for the program to produce the corresponding matrix. I have looked up problems on the scanf function, but none of the solutions I tried seemed to work...Could you help me out with this?
My code:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char a[3][3];
int i,j;
for(i=0;i<3;++i)
{
for(j=0;j<3;++j)
{
scanf("%c",&a[i][j]);
}
scanf("\n");
}
for(i=0;i<3;++i)
{
for(j=0;j<3;++j)
{
printf("%c",a[i][j]);
}
printf("\n");
}
system("PAUSE");
return(0); }
scanf("%c",...) get the whitespaces and the \n. You can solve it in many ways:
If you read like a b c
for(i=0;i<3;++i)
{
for(j=0;j<3;++j)
{
scanf("%c",&a[i][j]);
cin.get(); //Get the spaces after each character and the \n at the end of each line
}
}
or you can simple use cin (read char/string inputs with scanf is always a problem)
for(i=0;i<3;++i)
{
for(j=0;j<3;++j)
{
cin >> a[i][j];
}
}
if you are reading like abc, you only have to substitute your scanf("\n") for a cin.get()
#João Menighin's answer surely works. If you want to avoid c++, this would work:
for(i=0;i<3;++i)
{
for(j=0;j<3;++j)
{
scanf(" %c",&a[i][j]);
}
}
Although it would ignore ALL whitespace: both abc and a b c would be interpreted to be equivalent.
try adding a white space in your scanf right after the "
scanf(" %c",&a[i][j]);
I had the same problem in a two-dimension matrix and it worked for me.
I have no idea why though!!! I just spent 1 hour in front of my laptop trying different things...
Have tried your and IT WORKED. Although, I did make a few changes per comments:
#include <stdio.h> // added, but that shouldn't matter
main()
{
char a[3][3];
int i,j;
for(i=0;i<3;++i)
{
for(j=0;j<3;++j)
{
scanf("%c",&a[i][j]);
}
//scanf("\n"); // not necessary, see below
}
for(i=0;i<3;++i)
{
for(j=0;j<3;++j)
{
printf(" %c",a[i][j]);
}
printf("\n");
}
return(0);
}
Compiled and ran this code on Eclipse/Microsoft C Compiler and entered series of characters followed by enter.
abcdefghi
a b c
d e f
g h i
The point of confusion might be that scanf pulls the data from a console buffer. Typically, (although you can work around this) that buffer is returned to your program when you press enter. Also, the format specifier of %c also accepts blanks. Thus, I tried a second run with the following input and output.
a b c d e
a b
c
d e
You can tell the spaces were read and stored as well as the letters.
Hope this helps.