suggest me when will the following warning occurs during compilation - cc

temp....is used wrong in call to sprintf or snprintf.
If copying takes place bteween objects that overlap as a result of a call to sprintf() or snprintf(), results are undefined.

This doesn't provoke a warning from gcc, even with -Wall -Wextra -pedantic:
#include "stdio.h"
int main (void) {
char xx[1000] = "hello";
sprintf (xx, "xyzzy plugh %s", xx);
printf ("%s\n", xx);
return 0;
}
However, the reason why this is considered a bad idea can be seen from the output. Rather than getting:
xyzzy plugh hello
as a normal person may expect, you actually get:
xyzzy plugh xyzzy plugh
but, as with all undefined behaviour, your mileage may vary.
The definitive reference is the C99 standard, section 7.19.6.6 The sprintf function, which states:
The sprintf function is equivalent to fprintf, except that the output is written into an array (specified by the argument s) rather than to a stream. A null character is written at the end of the characters written; it is not counted as part of the returned value. If copying takes place between objects that overlap, the behavior is undefined.
The C++ standard (well, actually the C++0x draft, but it's surely due any day now, hopefully - c'mon guys, get it out there) references this since it incorporates parts of the C standard as deprecated functionality.

Related

TCL API coverage : check if a TCL command have been called and tested exaustively in a test suite

Supposing I have a TCL API like :
namespaceXY::apiXY <value> -opt1 <value1> -opt2 <value2> -opt3 <value3>
This API is used (or maybe not) in a test suite (i.e thousands of tests).
How I can check if my API have been called + tested exhaustively (all options have been called/tested).
Many thanks
You can set an execution trace on the command. That way the signature of your command won't change. So you still get the same results if any code does info args namespaceXY::apiXY. Also error messages are not affected.
proc cmdtracer {cmd op} {
global cmdtracer
dict incr cmdtracer $cmd
}
trace add execution namespaceXY::apiXY enter cmdtracer
In the end you'll have a cmdtracer dict that contains the counts of each way the command was called. You will have to figure out yourself how to check if all options have been tested. There is not enough information in your question to provide suggestions for that part.
See #SchelteBron's answer for covering commands.
Exhaustively testing all options is going to be tricky, since they could potentially all interact in complex ways and some may be mutually-exclusive (think about the standard Tcl lsearch command for example). However, auditing that all options are at least called in your own commands can be done by additional audit-only probes. Checking all the sensible combinations of them is a manual task; you probably need a coverage tool for that.
Auditing Options in C Commands
Assuming that you're dealing with the case where you've got a C command that uses Tcl_GetIndexFromObj() to parse the option name (this is common and recommended) and where you don't mind having a threading hazard (also pretty common) the idea is simple. Make an integer variable (probably with file scope) in your C code, bind it to a Tcl variable with Tcl_LinkVar(), then use the resulting index from your (successful) Tcl_GetIndexFromObj() call to set a bit in that integer variable that says that the option was parsed.
#ifdef AUDIT_OPTIONS
static int foobar_optionTracker;
#endif
// in the implementation function, called FoobarImpl here for sake of argument
int index;
if (Tcl_GetIndexFromObj(interp, objPtr, optionNameTable, "option", 0, &index) != TCL_OK) {
return TCL_ERROR;
}
#ifdef AUDIT_OPTIONS
foobar_optionTracker |= 1 << index;
// Theoretically should call Tcl_UpdateLinkedVar() here, but for audit-only its not important
#endif
switch (index) {
// ...
}
// In your command registration function
Tcl_CreateObjCommand(interp, "foobar", FoobarImpl, NULL, NULL);
#ifdef AUDIT_OPTIONS
Tcl_LinkVar(interp, "optionTracker(foobar)", (void*) &foobar_optionTracker, TCL_LINK_INT);
#endif
With that in place, you can just read the array element optionTracker(foobar) from your Tcl test control code to see what options have been parsed (assuming you're happy with a bit-mask) in the foobar command since the last time the mask was reset. You reset the mask by just writing 0 to it.
Note that there's also Tcl_GetIndexFromObjStruct() in the C API, but auditing coverage of that is not significantly different from above.
Auditing Options in Tcl Commands
The equivalent of Tcl_GetIndexFromObj() in pure Tcl code is tcl::prefix match, but that doesn't return an index. Instead it returns the full option name that you can use with switch. Auditing that is most easily done with a full array. (This is morally the same as what the version for the C code does, but adapted to work with the optimal tools in a particular language.)
proc foobar {mandatoryArgument1 mandatoryArgument2 args} {
# Parse other things here, set up the TABLE of option descriptors, etc.
foreach option $args {
set option [tcl::prefix match $TABLE $option]
if {$::DoAudit} {
set ::foobarAudit($option) 1
}
switch -- $option {
# etc...
}
}
You can use things like array size foobarAudit to count the number of options actually used, or parray foobarAudit to print out what was actually used.

Why is 'bicrement' not possible like this?

Why is this not possible?
int c = 0;
++c++;
Or in PHP:
$c = 0;
++$c++;
I would expect it to increment the variable c by 2, or perhaps do something weird, but instead it gives an error while compiling. I've tried to come up with a reason but got nothing really... My reasoning was this:
The compiler reads ++
It reads the variable
It does whatever it does to make the value of the variable increment and then get returned when executing the application
It encounters another ++
It uses the previous variable in order to return it before incrementing the value
This is where it gets confusing: does it use the variable c, or does it try to read the value that (++c) returned? Or, since you can only do varname++ (and not 2++), does it see (++c) as a pointer and then tries to read that memory location? Whatever it does, why would it give a compile error? Or is the error preventive, because the compiler's programmer knew it wouldn't do anything useful?
It's not really that I would want to use this, and certainly not for code that is not one-time use only, but I'm just curious.
For the same reason you can't do:
c++ = 5;
It returns a value, which cannot be modified nor assigned to. That's not a runtime error, either - that's a compilation error. (Like this one.)
Returning a reference wouldn't make sense either, because then:
$a = 1;
$b = $a++; // How can it be a reference if b should be 1 and a should be 2?
This isn't necessarily language-agnostic, although I'd be a little surprised to see a language in which it was different.
In C (and hence I assume in all non-annoying languages based on C), the operator precedence means your expression is equivalent to ++(c++). Based on your step-by-step, you were expecting it to be equivalent to (++c)++, but it isn't. Postfix ++ "binds more tightly" than prefix ++.
Like everyone says, the expression c++ results in a value, not a modifiable object (an expression in C that refers to an object is called an lvalue). This is necessary because the object c no longer holds the value that the expression evaluates to -- there is no object that c++ could refer to.
In C++ (not to be confused with c++!), ++c is an lvalue. It refers to the object c, which now has the new value.
So in C++ (++c)++ is syntactically correct. It happens to have undefined behavior if c is of type int (at least, it did in C++03: C++11 made some things defined that used to be undefined and I'm not up to date on those changes).
So, if you imagine (or go ahead and invent) a C++-like language in which the operator precedence is what you expected, then you could arrange for ++c++ to be valid. Presumably it would increment c twice, and evaluate to the value in between the old and new values. This imagined language would be "annoying" in the sense that it's only subtly different from C++, which would tend to be confusing.
++c++ is also valid in C++ if c is an instance of a user-defined type that overloads both increment operators. The reason is that an rvalue of user-defined type is an object (a "temporary object"), and can be modified. But as soon as the expression has been evaluated, the temporary is destroyed and the modification is lost.
Another way to Explain this is that the ++ operator only operates on an lvalue. But when you combine them, it's parsed as either ++(c++) or (++c)++ -- in either case, the parameter to the operator outside the parentheses is an rvalue (c's value before or after the increment), not an lvalue.

Is there any advantage in specifying types of variables and return type of functions?

I always set the types of my variables and functions, a habit I brought from my Java learning, seems the right thing to do.
But I always see "weak typing" in other people's code, but I can't disagree with that as I don't know what are the real advantages of keep everything strong typed.
I think my question is clear, but I gonna give some examples:
var id = "Z226";
function changeId(newId){
id = newId;
return newId;
}
My code would be like this:
var id:String = "Z226";
function changeId(newId:String):String{
id = newId;
return newId;
}
Yes, the big advantanges are:
faster code execution, because the runtime know the type, it does not have to evaluate the call
better tool support: auto completion and code hints will work with typed arguments and return types
far better readability
You get performance benefits from strongly typing. See http://gskinner.com/talks/quick/#45
I also find strongly typed code to be much more readable, but I guess depending on the person they may not care.
As pointed out by florian, two advantages of strongly typing are that development tools can can use the information to provide better code-hinting and code-completion, and that type, as an explicit indicator of how the variable or method is intended to be used, can make the code much easier to understand.
The question of performance seems to be up for debate. However, this answer on stackoverflow suggests that typed is definitely faster than untyped in certain benchmark tests but, as the author states, not so much that you would notice it under normal conditions.
However, I would argue that the biggest advantage of strong typing is that you get a compiler error if you attempt to assign or return a value of the wrong type. This helps prevent the kind of pernicious bug which can only be tracked down by actually running the program.
Consider the following contrived example in which ActionScript automatically converts the result to a string before returning. Strongly typing the method's parameter and return will ensure that the program will not compile and a warning is issued. This could potentially save you hours of debugging.
function increment(value) {
return value + 1;
}
trace(increment("1"));
// 11
While the points in the other answers about code hinting and error checking are accurate, I want to address the claim about performance. It's really not all that true. In theory, strong type allows the compiler to generate code that's closer to native. With the current VM though, such optimization doesn't happen. Here and there the AS3 compiler will employ an integer instruction instead of a floating point one. Otherwise the type indicators don't have much effect at runtime.
For example, consider the following code:
function hello():String {
return "Hello";
}
var s:String = hello() + ' world';
trace(s);
Here're the AVM2 op codes resulting from it:
getlocal_0
pushscope
getlocal_0
getlocal_0
callproperty 4 0 ; call hello()
pushstring 12 ; push ' world' onto stack
add ; concatenate the two
initproperty 5 ; save it to var s
findpropstrict 7 ; look up trace
getlocal_0 ; push this onto stack
getproperty 5 ; look up var s
callpropvoid 7 1 ; call trace
returnvoid
Now, if I remove the type indicators, I get the following:
getlocal_0
pushscope
getlocal_0
getlocal_0
callproperty 3 0
pushstring 11
add
initproperty 4
findpropstrict 6
getlocal_0
getproperty 4
callpropvoid 6 1
returnvoid
It's exactly the same, except all the name indices are one less since 'String' no longer appears in the constant table.
I'm not trying to discourage people from employing strong typing. One just shouldn't expect miracle on the performance front.
EDIT: In case anyone is interested, I've put my AS3 bytecode disassembler online:
http://flaczki.net46.net/codedump/
I've improved it so that it now dereferences the operands.

Embedded ECL Lisp error handling fetch default error string and possibly line number

Please see #7755661 first. I am using ECL and basically want to execute some code, trap any kind of condition that may occur and then continue execution, without prompting or entering the debugger. This is easy to achieve with the following handler-case macro:
(handler-case
(load "code.lisp") ; this may raise a condition
(error (condition)
(print condition))) ; this prints sth like #<a UNBOUND-VARIABLE>
My only problem is that I cannot find a generic way to print a more meaningful error for the user. Indeed my application is an HTTP server and the output goes to a web page. code.lisp is written by the user and it can raise any kind of condition, I do now want to list them all in my code. I would just like to print the same error message I see on the REPL when I do not use handler-case, but in the HTML page, e.g. for an "unbound variable" error, a string like "The variable VAR is unbound".
By inspecting a condition object of type UNBOUND-VARIABLE I see it has two slots: SI:REPORT-FUNCTION, which is a compiled function and SI:NAME, set to the name of the variable in this case. I guess SI:REPORT-FUNCTION could be what I need to invoke but how can I call it? If I try:
(handler-case foo (error (condition) (SI::REPORT-FUNCTION condition)))
it tells me that SI:REPORT-FUNCTION is undefined. SI or SYS in ECL is a package for functions and variables internal to the implementation, but I don't worry if my code is not portable, as long as it works.
BTW in other kinds of condition objects there are also other apparently useful slots for my purpose, named SI:FORMAT-CONTROL and SI:FORMAT-ARGUMENT, but I cannot access any of them from my code too.
I was looking for somethink alike to the getMessage() method of Java exception objects in Lisp, but none of my sources ever mentions something like that.
Moreover, is there any hope to be able to get the line number in code.lisp where the error occurred too? Without that it would be difficult for the user to locate the problem in his code.lisp source file. I would really want to provide this information and stopping at the first error is acceptable for me.
In Common Lisp when print escaping is disabled, the error message is printed.
CL-USER > (handler-case
a
(error (condition)
(write condition :escape nil)))
The variable A is unbound.
#<UNBOUND-VARIABLE 4020059743>
Note that PRINT binds *print-escape* to T.
Using PRINC works - it binds *print-escape* to NIL.
CL-USER > (handler-case
a
(error (condition)
(princ condition)))
The variable A is unbound.
#<UNBOUND-VARIABLE 4020175C0B>
This is described in CLHS 9.1.3 Printing Conditions.
Also note, when you have an object, which has a slot and the value of this slot is a function, then you need to get the slot value using the function SLOT-VALUE and then use FUNCALL or APPLY and call the function with the correct arguments.
If you have a condition of type simple-condition then it has a format-control and a format-argument information. This is described with an example how to use it for FORMAT in CLHS Function SIMPLE-CONDITION-FORMAT-CONTROL, SIMPLE-CONDITION-FORMAT-ARGUMENTS
My answer below is based on one I already gave at the ECL mailing list. Actually I would claim that this is not an embedding problem, but a Lisp one. You want to get some information at the file position of the form which caused the error. This is not attached to a condition because conditions happen independently of whether the form evaluated was interpreted, compiled or part of a function that is already installed in the Lisp image. In other words, it is up to you to know the position of the file which is being read and do some wrapping that adds the information.
The following is nonstandard and prone to change: ECL helps you by defining a variable ext::source-location when LOAD is used on a source file. This variable contains a CONS that should NEVER be changed or stored by the user, but you can get the file as (CAR EXT:*SOURCE-LOCATION*) and the file position as (CDR EXT:*SOURCE-LOCATION*). The plan is then to embed your LOAD form inside a HANDLER-BIND
(defparameter *error-message* nil)
(defparameter *error-tag* (cons))
(defun capture-error (condition)
(setf *error*
(format nil "At character ~S in file ~S an error was found:~%~A"
(cdr ext:*source-location*)
(car ext:*source-location*)
condition)))
(throw *error-tag* *error-message*))
(defun safely-load (file)
(handler-bind ((serious-condition #'capture-error))
(catch *error-tag*
(load file)
nil)))
(SAFELY-LOAD "myfile.lisp") will return either NIL or the formatted error.
In any case I strongly believe that relying on LOAD for this is doomed to fail. You should create your own version of LOAD, starting from this
(defun my-load (userfile)
(with-open-file (stream userfile :direction :input :external-format ....whateverformat...)
(loop for form = (read stream nil nil nil)
while form
do (eval-form-with-error-catching form))))
where EVAL-FORM-.... implements something like the code above. This function can be made more sophisticated and you may keep track of file positions, line numbers, etc. Your code will also be more portable this way.
So please, read the ANSI Spec and learn the language. The fact that you did not know how to print readably a condition and instead tried to play with ECL internals shows that you might face further problems in the future, trying to go with non-portable solutions (hidden slot names, report functions, etc) instead of first trying the standard way.

How to evaluate functions in GDB?

I wonder why evaluate function doesn't work in gdb? In my source file I include, when debugging in gdb, these examples are wrong evaluations.
(gdb) p pow(3,2)
$10 = 1
(gdb) p pow(3,3)
$11 = 1
(gdb) p sqrt(9)
$12 = 0
The syntax for calling a function in gdb is
call pow(3,2)
Type
help call
at the gdb prompt for more information.
You need to tell gdb that it will find the return value in the floating point registers, not the normal ones, in addition to give the parameters the right types.
I.e.:
(gdb) p ((double(*)())pow)(2.,2.)
$1 = 4
My guess is that the compiler and linker does some magic with those particular functions. Most likely to increase performance.
If you absolutely need pow() to be available in gdb then you can create your own wrapper function:
double mypow(double a, double b)
{
return pow(a,b);
}
Maybe also wrap it into a #ifdef DEBUG or something to not clutter the final binary.
BTW, you will notice that other library functions can be called (and their return value printed), for instance:
(gdb) print printf("hello world")
$4 = 11
Actually, at least on my LINUX implementation of gcc, many of the math functions are replaced with variants specific to the types of their arguments via some fancy substitutions pulled in by math.h and bits/mathcalls.h (included from within math.h). As a consequence, functions like pow and exp are called instead as __pow or *__GI___exp (your results may vary depending on the types of the arguments and perhaps the particular version).
To identify what exactly the function is that is linked in to my code I put a break at a line where just that function is called, e.g. have a line in my code with b=exp(c);. Then I run in gdb up till that break point and then use the "step" command to enter the call from that line. Then I can use the "where" command to identify the name of the called routine. In my case that was *__GI___exp.
There are probably cleverer ways to get this information, however, I was not able to find the right name just by running the preprocessor alone (the -E option) or by looking at the assembly code generated (-s).
NAME
pow, powf, powl - power functions
SYNOPSIS
#include <math.h>
double pow(double x, double y);
You shouldn't pass an int in the place of a double
call pow( 3. , 2. )
Also, passing a single argument is not enough, you need two arguments just like the function expects
wrong: call pow ( 3. )