Why try ... except block is not working here - try-catch

I am trying to run following code with try.. except block:
program TriangleArea;
uses crt, sysutils;
type
num = real;
var
a, b, c, s, area : num;
begin
write('Enter lengths of 3 sides (separated by spaces): ');
try
readln (a, b, c);
s := (a + b + c)/2.0;
area := sqrt(s * (s - a)*(s-b)*(s-c));
writeln(area);
except
on E: Exception do
ShowMessage( 'Error: '+ E.ClassName + #13#10 + E.Message );
end;
end.
But it is giving following error:
$ fpc triangle_area.pas
Free Pascal Compiler version 3.0.0+dfsg-11+deb9u1 [2017/06/10] for x86_64
Copyright (c) 1993-2015 by Florian Klaempfl and others
Target OS: Linux for x86-64
Compiling triangle_area.pas
triangle_area.pas(14,2) Error: Identifier not found "try"
triangle_area.pas(15,3) Fatal: Syntax error, ";" expected but "identifier READLN" found
Fatal: Compilation aborted
Error: /usr/bin/ppcx64 returned an error exitcode
Why "try" identifier is not being found. I am using fpc version 3.0.0 on Debian stable Linux.
Where is the problem and how can it be solved? Thanks for your help.

Place {$MODE OBJFPC} or {$MODE DELPHI} beneath your program declaration.
The reason is that by default the compiler will compile in MODE FPC, which does not support exceptions.
Additional sources: One Two Three
On the other hand, the ShowMessage instruction will not compile with Free Pascal. The correct code is:
program TriangleArea;
{$mode delphi}
uses crt, sysutils;
type
num = real;
var
a, b, c, s, area : num;
begin
write('Enter lengths of 3 sides (separated by spaces): ');
try
readln (a, b, c);
s := (a + b + c)/2.0;
area := sqrt(s * (s - a)*(s-b)*(s-c));
writeln(area);
except
on E: Exception do
write( 'Error: '+ E.ClassName + #13#10 + E.Message );
end;
end.
Later edit: the declaration type num=real is correct, but I don't see any real use of it.

Related

C file not instrumented for coverage, bad expr node kind

I am using the legacy_code tool in MATLAB, to generate some S Functions, then I want the S Functions to be under analysis by the simulink coverage toolbox.
I am asking also here because maybe this is a C issue and not MATLAB related.
I am setting to true the flag to use the coverage toolbox when generating the S functions using the legacy_code tool.
def.Options.supportCoverage = true;
But I get the following error at compilation, I am using the MinGW 64 bits compiler for MATLAB in windows.
“lib_control.c", line 254: error: bad expr node kind (b:\matlab\polyspace\src\shared\cxx_front_end_kernel\edg\src\cp_gen_be.c, line 14084)
Warning: File "lib_control.c" not instrumented for coverage because of previous error
In codeinstrum.internal.LCInstrumenter/instrumentAllFiles
In codeinstrum.internal.SFcnInstrumenter/instrument
In slcovmexImpl
In slcovmex (line 48)
In legacycode.LCT/compile
In legacycode.LCT.legacyCodeImpl
In legacy_code (line 101)
In generate_sfun (line 70)
In the C code I have the following kind of functions:
void controller( int n_var,
double my_input,
double my_output )
{
double my_var[n_var];
for ( int i=0; i<n_var; i++ )
{
my_output = my_input + my_var[i];
}
}
The compiler is complaining about this line:
double my_var[n_var];
Do I have to do something to declare variables like this, so they can be included in the coverage analysis?
Is this error from MATLAB or is it a C error for instrumentation of files?
If I compile without the coverage flag there is no problems and the S Functions is generated without warnings.
Seems your code won't work because of issues.
First try to declare my_var like this
double *my_var = malloc(n_var * sizeof(double));
memset(my_var, 0, n_var * sizeof(double));
This is the correct way to allocate memory according to function parameter.
And there is also an issue.
my_output = my_input + my_var[i];
So it is correct solution.
*my_output = *my_input + my_var[i];
You are going to change value of parameter which is stack register variable
In C language, parameters are saved in to stack register so it will be freed after function ends.
so it won't reflect any changes
To do this, you need to send pointer of variable as parameter
void controller( int n_var,
double *my_input,
double *my_output ) {
*my_output = ....; // like this
}
and in caller side, you can do like this.
double a, b;
controller(10, &a, &b);
Hope this helps you

Coq VST Internal structure copying

run into a problem with VST(Verified Software Toolchain) 2.5v library for Coq 8.10.1:
Got an error with the latest working commit of VST namely "Internal structure copying is not supported".
Minimal example:
struct foo {unsigned int a;};
struct foo f() {
struct foo q;
return q; }
On starting proof got an error:
Error: Tactic failure: The expression (_q)%expr contains internal structure-copying, a feature of C not currently supported in Verifiable C (level 97).
This is due to the check_normalized in floyd/forward.v :
Fixpoint check_norm_expr (e: expr) : diagnose_expr :=
match e with
| Evar _ ty => diagnose_this_expr (access_mode ty) e
...
So, the questions are:
1) What suggested workarounds exists?
2) What is the reason for this limitation?
3) Where can I get a list of unsupported features?
1) The workaround is to change your C program to copy field by field.
2) The reason is the absurdly complicated and target-ISA-dependent implementation/semantics of C's structure-copying, especially in parameter passing and function-return.
3) The first 10 lines of Chapter 4 ("Verifiable C and clightgen") of the reference manual has a short list of unsupported features, but unfortunately struct-by-copy is not on that list. That's a bug.

R Package: Call C Function Within Rcpp

I am writing an R package that contains C and Rcpp. The goal is to call the C function from R and within Rcpp, eventually performing most of the analysis in Rcpp and only returning to R for minimal tasks. My package compiles and calling my function from R works fine.
#generate some matrix. Numeric is fine too. Must have column names, no row names
myMat <- matrix(data = 1:100, nrow = 10, ncol = 10,
dimnames = list(NULL, LETTERS[1:10]))
#This works. Put in full path, no expansion. It returns null to the console.
MinimalExample::WriteMat(mat = myMat, file = "Full_Path_Please/IWork.csv",
sep = "," ,eol = "\n", dec = ".", buffMB = 8L)
However, attempting the same thing in Rcpp produces a SIGSEV error. I think the problem is how I am passing arguments to the function, but I can't figure out the proper way.
#include <Rcpp.h>
using namespace Rcpp;
extern "C"{
#include "fwrite.h"
}
//' #export
// [[Rcpp::export]]
void WriteMatCpp(String& fileName, NumericMatrix& testMat){
Rcpp::Rcout<<"I did start!"<<std::endl;
String patchName = fileName;
int whichRow = 1;
std::string newString = std::string(3 - toString(whichRow).length(), '0')
+ toString(whichRow);
patchName.replace_last(".csv", newString+".csv");
//Set objects to pass to print function
String comma = ",";
String eol = "\n";
String dot = ".";
int buffMem = 8;
//This is where I crash, giving a SIGSEV error
fwriteMain(testMat, (SEXP)&patchName, (SEXP)&comma, (SEXP)&eol,
(SEXP)&dot, (SEXP)&buffMem);
}
Here is a link to the GitHub repository with the package. https://github.com/GilChrist19/MinimalExample
Your call from C++ to C is wrong. You can't just write (SEXP)& in front of an arbitrary data structure and hope for it to become a SEXP.
Fix
Use a line such as this to convert what you have in C++ to the SEXP your C function expects using Rcpp::wrap() on each argument:
//This is where I crash, giving a SIGSEV error
fwriteMain(wrap(testMat), wrap(patchName), wrap(comma),
wrap(eol), wrap(dot), wrap(buffMem));
Demo
edd#brad:/tmp/MinimalExample/MinEx(master)$ Rscript RunMe.R
I did start!
edd#brad:/tmp/MinimalExample/MinEx(master)$ cat /tmp/IDoNotWork.csv
A,B,C,D,E,F,G,H,I,J
1,11,21,31,41,51,61,71,81,91
2,12,22,32,42,52,62,72,82,92
3,13,23,33,43,53,63,73,83,93
4,14,24,34,44,54,64,74,84,94
5,15,25,35,45,55,65,75,85,95
6,16,26,36,46,56,66,76,86,96
7,17,27,37,47,57,67,77,87,97
8,18,28,38,48,58,68,78,88,98
9,19,29,39,49,59,69,79,89,99
10,20,30,40,50,60,70,80,90,100
edd#brad:/tmp/MinimalExample/MinEx(master)$
See https://github.com/GilChrist19/MinimalExample/tree/master/MinEx for a complete example.

Error using namelist in gfortran

I am trying to read certain values from a test file, but gfortran keeps giving me an end of file error and I am not sure why. Here is the Fortran code:
program mesh
implicit real*8(a-h,o-z)
namelist /input/ x
open(5,file='input.in')
read(5,input)
print*, x
end program mesh
Here is my input file:
&input
x=5/
I have tried multiple input files with using &end instead of / and having everything on the same line (with spaces).
It should works once you move the "/" to a new line. The EOL character did not have any effect with gfortran version 4.6.3
&input
x=5
/
Although you've already got the correct answer, the simplest way to determine the format is to write a program to create a namelist file and then look at it for correct syntax.
Here's your program modified to do that [and I've added a second namelist]:
program mesh
implicit real*8(a-h,o-z)
namelist /input/ x,y
namelist /input2/ a,c
x = 4
y = 7
a = 37
b = 23
open(5,file='input.in')
write(5,input)
write(5,input2)
end program mesh
The generated file is:
&INPUT
X= 4.0000000000000000 ,
Y= 7.0000000000000000 ,
/
&INPUT2
A= 37.000000000000000 ,
C= 0.0000000000000000 ,
/

Watch out for C function names with R code

So here is something a bit crazy.
If you have some C code which is called by an R function (as a shared object), try adding this to the code
void warn() {
int i; // just so the function has some work, but you could make it empty to, or do other stuff
}
If you then call warn() anywhere in the C code being called by the R function you get a segfault;
*** caught segfault ***
address 0xa, cause 'memory not mapped'
Traceback:
1: .C("C_function_called_by_R", as.double(L), as.double(G), as.double(T), as.integer(nrow), as.integer(ncolL), as.integer(ncolG), as.integer(ncolT), as.integer(trios), as.integer(seed), as.double(pval), as.double(pval1), as.double(pval2), as.double(pval3), as.double(pval4), as.integer(ntest), as.integer(maxit), as.integer(threads), as.integer(quietly))
2: package_name::R_function(L, G, T, trios)
3: func()
4: system.time(func())
5: doTryCatch(return(expr), name, parentenv, handler)
6: tryCatchOne(expr, names, parentenv, handlers[[1L]])
7: tryCatchList(expr, classes, parentenv, handlers)
8: tryCatch(expr, error = function(e) { call <- conditionCall(e) if (!is.null(call)) { if (identical(call[[1L]], quote(doTryCatch))) call <- sys.call(-4L) dcall <- deparse(call)[1L] prefix <- paste("Error in", dcall, ": ") LONG <- 75L msg <- conditionMessage(e) sm <- strsplit(msg, "\n")[[1L]] w <- 14L + nchar(dcall, type = "w") + nchar(sm[1L], type = "w") if (is.na(w)) w <- 14L + nchar(dcall, type = "b") + nchar(sm[1L], type = "b") if (w > LONG) prefix <- paste(prefix, "\n ", sep = "") } else prefix <- "Error : " msg <- paste(prefix, conditionMessage(e), "\n", sep = "") .Internal(seterrmessage(msg[1L])) if (!silent && identical(getOption("show.error.messages"), TRUE)) { cat(msg, file = stderr()) .Internal(printDeferredWarnings()) } invisible(structure(msg, class = "try-error", condition = e))})
9: try(system.time(func()))
10: .executeTestCase(funcName, envir = sandbox, setUpFunc = .setUp, tearDownFunc = .tearDown)
11: .sourceTestFile(testFile, testSuite$testFuncRegexp)
12: runTestSuite(testSuite)
aborting ...
Segmentation fault (core dumped)
(END)
Needless to say the code runs fine if you call the same function from a C or C++ wrapper instead of from an R function. If you rename warn() it also works fine.
Any ideas? Is this a protected name/symbol? Is there a list of such names? I'm using R version 2.14.1 on Ubuntu 12.01 (i686-pc-linux-gnu (32-bit)). C code is compiled with GNU GCC 4.6.3.
This seems like quite an interesting question. Here's my minimal example, in a file test.c I have
void warn() {}
void my_fun() { warn(); }
I compile it and then run
$ R CMD SHLIB test.c
$ R -e "dyn.load('test.so'); .C('my_fun')"
With my linux gcc version 4.6.3., the R output is
> dyn.load('test.so'); .C('my_fun')
R: Success
list()
with that "R: Success" coming from the warn function defined in libc (see man warn, defined in err.h). What happens is that R loads several dynamic libraries as a matter of course, and then loads test.so as instructed. When my_fun gets called, the dynamic linker resolves warn, but the rules of resolution are to search globally for the warn symbol, and not just in test.so. I really don't know what the global search rules are, perhaps in the order the .so's were opened, but whatever the case the resolution is not where I was expecting.
What is to be done? Specifying
static void warn() {}
forces resolution at compile time, when the .o is created, and hence avoiding the problem. This wouldn't work if, for instance, warn was defined in one file (utilities.c) and my_fun in another. On Linux dlopen (the function used to load a shared object) can be provided with a flag RTLD_DEEPBIND that does symbol resolution locally before globally, but (a) R does not use dlopen that way and (b) there are several (see p. 9) reservations with this kind of approach. So as far as I can tell the best practice is to use static where possible, and to carefully name functions to avoid name conflicts. This latter is not quite as bad as it seems, since R loads package shared objects such that the package symbols themselves are NOT added to the global name space (see ?dyn.load and the local argument, and also note the OS-specific caveats).
I'd be interested in hearing of a more robust 'best practice'.

Resources