atomic compare(not equal) and swap - c

I want to use atomic compare and swap, but instead of equal to, I want to swap only if the memory location is not equal to the old value. Is it possible in C?

How about this:
void compare_and_swap_if_not_equal(word_t const required_non_value, word_t const new_value, word_t* ptr_to_shared_variable) {
for (;;) {
word_t const snapshot_value = *ptr_to_shared_variable;
if (required_non_value == snapshot_value) {
break;
// or (sleep and) 'continue;', if you want to wait for the stored value to be different
// -- but you might of course miss a transient change to a different state and back.
} else {
if (compare_and_swap_if_equal(ptr_to_shared_variable, snapshot_value, new_value)) {
// we know the stored value was different; if this 'theory' still matches reality: swap! done!
break;
}
}
}
}
Untested. Uncompiled. The 'const' used because I like it that way :). 'word_t' is a type placeholder, I don't know what the real type should be. And I don't know how what 'compare_and_swap_if_equal' is called in stdatomic.h.
(added) atomic_compare_exchange_weak() is the ticket. For some reason, it takes a pointer to the 'expected' argument, so you'll have to modify above code to
if (atomic_compare_exchange_weak(ptr_to_shared_variable, &snapshot_value, new_value)) ...
The 'weak' version should work in the above code; returning 'false' spuriously will only add another trip around the loop. Still uncompiled, untested; don't rely on this code at home.

It depends on your architecture, but in general it is not possible to do this in C.
Typically compare and swap is implemented with an instruction that atomically loads from a location in memory and stores a value to that location if the location in memory matches some existing value that you specify.
At least on x86 there is no provision for only doing this load if the values don't match. Also it's not clear why you would want to do something like that. Perhaps another architecture would support something like this, but that would be architecture dependent, not something that could be done in C in a portable way.

Related

Unpermitted operand to operator '++' [MISRA 2012 Rule 10.1, required]

I am trying to fix the Misra warning for the modules written by others. I observed that ++ operation is being used on the enum.
I referred SE question which talks on the same topic. How do I resolve this error? Do I need to suggest the module owner, to change the implementation?
#include <stdio.h>
typedef enum
{
COMPARE = 0,
INCONSISTENT = 10,
WRITE,
READ,
FINISHED
}TestsType;
static TestsType CurrentTest;
void fun1(void)
{
if(READ != CurrentTest)
{
CurrentTest++;
}
else
{
CurrentTest = FINISHED;
}
}
int main(void) {
// your code goes here
CurrentTest = COMPARE;
fun1();
printf("%d", CurrentTest);
return 0;
}
I kept the enum like this in code purposefully to understand any impact. However, in actual code, it is as below.
typedef enum
{
COMPARE,
INCONSISTENT,
WRITE,
READ,
FINISHED
}TestsType;
Incrementing an enum is just wrong!
enums were added to the language as a better alternative to #define for a number of constants, and were considered ints in other respects (i.e. a const array of ints). To enforce anything more would require run-time checking.
As enum values don't have to be contiguous, incrementing them makes no sense when they're treated as integers. If a compiler does allow it, it thinks it's incrementing an int, which can mean your value doesn't correspond to any value in the enum afterwards.
So my advice is "don't do it" even if a particular compiler lets you. Rewrite it to something explicit.
If you want to cycle through a particular range of states represented by contiguous integers, you CAN use an enum but only if you make its values contiguous too. Put lots of warnings about the definition explaining not to tinker. Then increment an int representing the state, which can then be compared to the enum safely.
The whole point of using a standard like MISRA is to avoid risky code. And there's no question but that incrementing enums is risky.
If you've got some code that increments enums, and it works well (under all conditions), it's only because of a number of interlocked assumptions and conventions which probably aren't all written down and which almost certainly won't be obvious to (and honored by) a later maintenance programmer.
So, indeed, there is no simple fix for this. Any simple fix (which might get your MISRA checker to shut up) will likely leave the inherent risks in the practice all intact -- that is, you might satisfy the letter of MISRA, but not the spirit (which is obviously backwards).
So yes, you should require (not just suggest) that the module owner change the implementation.
What might the revised implementation look like? I think it should have one or more of the following aspects:
Use an int and some #defined constants.
Have a separate, encapsulated function to map from one state to the next.
Use an explicit transition table to map one state to the next.
If there is a large number of states, and if most of them follow in sequence, such that a +1 increment would nicely encapsulate this (more cleanly and reliably than a bunch of arbitrary state transitions), go ahead and use a +1 increment, but with some accompanying assertions to ensure that the various assumptions hold. For example:
enum state {
OFF = 0,
LOW = 3,
MEDIUM,
HIGH,
EXCEPTIONAL = 10
};
/* States LOW..HIGH are assumed to be contiguous. Make sure you keep them so! */
/* If (and only if) you add or subtract states to the contiguous list, */
/* make sure to also update N_CONTIGUOUS_STATES. */
#define N_CONTIGUOUS_STATES 3
enum state nextstate(enum state oldstate)
{
/* Normally performing arithmetic on enums is wrong. */
/* We're doing so here in a careful, controlled, constrained way, */
/* limited just to the values LOW..HIGH which we're calling "contiguous". */
assert((int)LOW + N_CONTIGUOUS_STATES - 1 == (int)HIGH);
if(oldstate >= LOW && oldstate < HIGH) {
return (enum state)((int)oldstate + 1);
} else {
/* perform arbitrary mappings between other states */
}
}
The intent here is both to document what's going on, and ensure that if a later maintenance programmer changes the enum definition in any way that breaks the assumption that there are some consecutive states between which straight incrementation is allowed, the assertion will fail.
...But I hasten to add that this is not a complete solution. An even more important guarantee to preserve is that every state transition is handled, and this is even easier to violate if a later maintenance programmer adds new states but forgets to update the transition mappings. One good way to have the compiler help you guarantee this is to use a switch statement, although this then just about forces you to make every transition explicit (that is, not to use the +1 shortcut):
enum state nextstate(enum state oldstate)
{
switch(oldstate) {
case OFF: return ... ;
case LOW: return MEDIUM;
case MEDIUM: return HIGH;
case HIGH: return ... ;
case EXCEPTIONAL: return ... ;
}
}
The advantage of using a switch is that modern compilers will warn you if you leave an enum value out of a switch like this.

Saw a strange if statement in some legacy C code

What I saw in an if statement was like this.
if((var = someFunc()) == 0){
...
}
Will the statement
(var = someFunc())
always return the final value of var no matter what environment we are in?
That is just a one-line way of assigning to a variable and comparing the returned value at the same time.
You need the parentheses around the assignment because the comparison operators have higher precedence than the assignment operator, otherwise var would be assigned the value of someFunc() == 0.
This is simply wrong. var is assigned, and then its value is overwritten by a constant 0. The return value of the function is therefore lost, and the if always fails. Most compilers would probably issue a warning about that nowadays, both because of the assignment within an if and because of the impossible if that results. The right way to do what was probably intended is
if((var = someFunc()) == 0) {
(Mind you, this might also be malicious code trying to introduce a vulnerability under the guise of a common newbie mistake. There was a case recently where someone tried to smuggle a check into the Linux kernel where they assigned the UID to 0 (i.e., root) while pretending to check for being root. Didn't work, though.)
This is correct, I use it all the time
if ((f=fopen(s,"r"))==NULL)
return(fprintf(stderr,"fopen(%s,r) failed, errno=%d, %s\n",s,errno,strerror(errno)));
/* successfully opened file s, read from FILE *f as you like */
I also use it when I calloc() memory.
You're assigning the return value of someFunc (fopen or calloc in my cases) to a variable AND also testing that return value, it's a semantic shortcut assuming you'll never want to debug the assignment and the test separately.

Designing Around a Large Number of Discrete Functions in C

Greetings and salutations,
I am looking for information regrading design patterns for working with a large number of functions in C99.
Background:
I am working on a complete G-Code interpreter for my pet project, a desktop CNC mill. Currently, commands are sent over a serial interface to an AVR microcontroller. These commands are then parsed and executed to make the milling head move. a typical example of a line might look like
N01 F5.0 G90 M48 G1 X1 Y2 Z3
where G90, M48, and G1 are "action" codes and F5.0, X1, Y2, Z3 are parameters (N01 is the optional line number and is ignored). Currently the parsing is coming along swimmingly, but now it is time to make the machine actually move.
For each of the G and M codes, a specific action needs to be taken. This ranges from controlled motion to coolant activation/deactivation, to performing canned cycles. To this end, my current design features a function that uses a switch to select the proper function and return a pointer to that function which can then be used to call the individual code's function at the proper time.
Questions:
1) Is there a better way to resolve an arbitrary code to its respective function than a switch statement? Note that this is being implemented on a microcontroller and memory is EXTREMELY tight (2K total). I have considered a lookup table but, unfortunately, the code distribution is sparse leading to a lot of wasted space. There are ~100 distinct codes and sub-codes.
2) How does one go about function pointers in C when the names (and possibly signatures) may change? If the function signatures are different, is this even possible?
3) Assuming the functions have the same signature (which is where I am leaning), is there a way to typedef a generic type of that signature to be passed around and called from?
My apologies for the scattered questioning. Thank you in advance for your assistance.
1) Perfect hashing may be used to map the keywords to token numbers (opcodes) , which can be used to index a table of function pointers. The number of required arguments can also be put in this table.
2) You don's want overloaded / heterogeneous functions. Optional arguments might be possible.
3) your only choice is to use varargs, IMHO
I'm not an expert on embedded systems, but I have experience with VLSI. So sorry if I'm stating the obvious.
The function-pointer approach is probably the best way. But you'll need to either:
Arrange all your action codes to be consecutive in address.
Implement an action code decoder similar to an opcode decoder in a normal processor.
The first option is probably the better way (simple and small memory footprint). But if you can't control your action codes, you'll need to implement a decoder via another lookup table.
I'm not entirely sure on what you mean by "function signature". Function pointers should just be a number - which the compiler resolves.
EDIT:
Either way, I think two lookup tables (1 for function pointers, and one for decoder) is still going to be much smaller than a large switch statement. For varying parameters, use "dummy" parameters to make them all consistent. I'm not sure what the consequences of force casting everything to void-pointers to structs will be on an embedded processor.
EDIT 2:
Actually, a decoder can't be implementated with just a lookup table if the opcode space is too large. My mistake there. So 1 is really the only viable option.
Is there a better way ... than a switch statement?
Make a list of all valid action codes (a constant in program memory, so it doesn't use any of your scarce RAM), and sequentially compare each one with the received code. Perhaps reserve index "0" to mean "unknown action code".
For example:
// Warning: untested code.
typedef int (*ActionFunctionPointer)( int, int, char * );
struct parse_item{
const char action_letter;
const int action_number; // you might be able to get away with a single byte here, if none of your actions are above 255.
// alas, http://reprap.org/wiki/G-code mentions a "M501" code.
const ActionFunctionPointer action_function_pointer;
};
int m0_handler( int speed, int extrude_rate, char * message ){ // M0: Stop
speed_x = 0; speed_y = 0; speed_z = 0; speed_e = 0;
}
int g4_handler ( int dwell_time, int extrude_rate, char * message ){ // G4: Dwell
delay(dwell_time);
}
const struct parse_item parse_table[] = {
{ '\0', 0, unrecognized_action } // special error-handler
{ 'M', 0, m0_handler }, // M0: Stop
// ...
{ 'G', 4, g4_handler }, // G4: Dwell
{ '\0', 0, unrecognized_action } // special error-handler
}
ActionFunctionPointer get_action_function_pointer( char * buffer ){
char letter = get_letter( buffer );
int action_number = get_number( buffer );
int index = 0;
ActionFunctionPointer f = 0;
do{
index++;
if( (letter == parse_table[index].action_letter ) and
(action_number == parse_table[index].action_number) ){
f = parse_table[index].action_function_pointer;
};
if('\0' == parse_table[index].action_letter ){
index = 0;
f = unrecognized_action;
};
}while(0 == f);
return f;
}
How does one go about function pointers in C when the names (and
possibly signatures) may change? If the function signatures are
different, is this even possible?
It's possible to create a function pointer in C that (at different times) points to functions with more or less parameters (different signatures) using varargs.
Alternatively, you can force all the functions that might possibly be pointed to by that function pointer to all have exactly the same parameters and return value (the same signature) by adding "dummy" parameters to the functions that require fewer parameters than the others.
In my experience, the "dummy parameters" approach seems to be easier to understand and use less memory than the varargs approach.
Is there a way to typedef a generic type of that signature
to be passed around and called from?
Yes.
Pretty much all the code I've ever seen that uses function pointers
also creates a typedef to refer to that particular type of function.
(Except, of course, for Obfuscated contest entries).
See the above example and Wikibooks: C programming: pointers to functions for details.
p.s.:
Is there some reason you are re-inventing the wheel?
Could maybe perhaps one of the following pre-existing G-code interpreters for the AVR work for you, perhaps with a little tweaking?
FiveD,
Sprinter,
Marlin,
Teacup Firmware,
sjfw,
Makerbot,
or
Grbl?
(See http://reprap.org/wiki/Comparison_of_RepRap_Firmwares ).

function returning optional value

Whenever we call a function returning value why it is not required to catch the value?
consider the following C code,
int main()
{
int i;
scanf("%d",&i);
printf("Value of i is: ",i);
return 0;
}
Here scanf() returns value 1, but as it is not catched in anywhere why didn't the error pops up?
What is the reason to allow such programming?
Primarily because expressions in C also yield values. For example: x = 1; yields the value 1. Sometimes you use that for multiple assignment like x = y = 1;, but more often you don't.
In early C, the void return type hadn't been invented either, so every function returned some value, whether it was generally useful or not (for example, your call to printf also returns a value).
The rules of the language don't make this an error (doing so would lose compatibility with virtually existing code) and since this is common and rarely indicates a problem, most compilers don't warning about it either. A few lint tools do, which has led a few misguided programmers to write things like (void)printf("whatever"); (i.e., casting the unused return to void to signal that it really, truly was intentional when it was ignored. This, however, rarely does any good, and frequently does quite a bit of harm, so (thankfully) it's rarely seen.
Functions that return a value have that functionality for the use and convenience of the programmer. If you aren't interested in the return value, then don't use it.
Do you need the return value in this example? NO. So you have not used that in this case. But in another situation the return value might be important. For example if you want to read as long as some integer in available in input stream, then you can do something like this:
while (scanf("%d", &i) == 1) {
// do something
}
If there is an EOF then this loop will break. Here return value is needed.
So the summary is use return value when needed, and don't use when not needed. Such programming is allowed because both scenario is possible.
A lot of library functions return values you might not think about. Imagine having to use the return value of every printf call! (printf returns the number of characters printed.)
Pretty much every native c function returns a int. scanf and printf included. It would be really annoying if you always had to "capture" it to satisfy the compiler; In a large program you would end up creating thousands of variables just for storing return values that you never look at.
The reason is that C has no other established way of handling errors than by return value. These returned values, that is to say those return to report success or failure, should almost always be checked (unless you're just doodling around or you have a proof that the function will not fail).
Now since return values are also used for other things than returning success/failure information there might be, and are, situations where you will not be interested in the value a function returns, but just the side effects of executing it. In this case forcing the programmer to inspect/bind the returned value would become quite tideous.
Simple: if you don't use the return value, you don't use it.
It is not mandated that you do.
(That said, in a case like this, you should: you have no idea at present whether scanf encountered an error.)
It is not the case that everytime a value is evaluated,& it must be stored or returned,because the value you have obtained may be used by some other functions,to evaluate different kind of things.A value may be a measure...for example consider the following simple programm,where we want to check that the number entered is even or not
'int main()
{
int a;
printf("Enter a number");
scanf("%d",&a);
if(a%2==0)
printf("even number");
else
printf("odd no");
return 0;
}'
here the variable 'a' is not necessarily to be returned,because we just want to check that the number is even or odd...no need of returning

How to return string from a char function

I want the function getCategory() to return "invalid" , instead of printing the word "invalid" (i.e instead of using printf ) when input to the function is invalid (i.e.when either height or weight are lower then zero).
please help:
#include<stdio.h>
#include<conio.h>
char getCategory(float height,float weight)
{
char invalid = '\0';
float bmirange;
if(height<=0 || weight<=0)
return invalid;
else
{
height=height*0.01; //1 centimeter = 0.01 meters
bmirange=[weight/(height*height)];
if(bmirange< 15 )
return starvation;
}
}
int main()
{
char Category;
float height,weight;
printf("enter height");
scanf("%f",&height);
printf("enter weight");
scanf("%f",&weight);
Category=getCategory(height,weight);
if(Category == 0)
printf("invalid");
else
printf("%c", Category);
}
NOTE: the original question has been altered many, many times and the code has changed just as often, introducing new errors in each iteration. I leave this answer as it answered the original code, see history. Below this answer there's an update giving advice instead of code, as that seems more appropriate here.
Hmm, astander removed his answer. But perhaps this is what you should actually have:*
char getCategory(float height,float weight)
{
char invalid = '\0';
if(height<=0 || weight<=0)
return invalid;
return 'c'; /* do something for the valid cases */
}
* originally the question contained height || weight <= 0 and no value for variable invalid.
Notes on the code:
With proper indentation, your program flow becomes clearer. I corrected your if-statement, assuming this was your intend, actually. The last line should contain what you currently left out in your question. I added an initialization in the first line, because having a value is better then not having a value (which means: if you don't initialize, it can be anything, really).
In your calling code, you can do this:
Category = getCategory(height, weight);
if(Category == 0)
printf("invalid");
else
printf("%c", Category);
which actually prints the word "invalid" to the output, if that was your intend.
Update: based on new text in the question, it's clear that the asker wants something else, so here's a new answer. I leave the above, it's still valid with the original question.
You're now asking not to print the word "invalid" and not to use a special value for the invalid case. Instead, you ask to return "invalid", which I understand as returning the string with the value "invalid" (which, taken in itself, is still returning a special value).
You cannot do it
In short: you cannot do that. The current function has return type char. I don't know the purpose of your function, but I'm sure you've given it some thought and there's a reason for using a char. A char can only contain one character. And the word "invalid" is multiple characters. You have a few options, choose whichever suits you best:
Other ways
change the return type to be string instead of char, this requires redesign of all code involved;
settle with returning a special value. You don't show the body of your function, but if it would normally never return \0, you can use that value, as in my example above. Of course, you can choose any other char value;
raise an exception and use a try/catch in the body. But you use C, not C++. Here's a link that describes using C++-style exception handling for C, but this may be a bit out-of-bounds, learning C can better be taken on a small step at the time.
What's commonly best practice
In normal situations, it is common to choose either special-case values (typical in older or more basic languages like C or assembler) or exceptions (typical for more structured languages like C++, Java, Python). It's commonly considered bad practice to change a complete function for the purpose of special-cases (like invalid input).
Why
Instead, the caller of the function should deal with these special cases. The reason for this is a very important rule in programming: the function can never know beforehand what users of that function want to do when something bad happens (illegal input). One may choose to print "Illegal input" (for commandline users), another wants to quit the program (for in a library) and yet another wants to ignore and do nothing (for automatic processing). In short: what you are trying to achieve, you should try to achieve differently (see option 2 and 3 above, and my original solution).
Teachers and textbooks
Using this approach is by far the easiest and also best to understand for any (future) co-workers as it follows common computer practices. Of course, I haven't seen your assignment or textbook, so I can't tell in what direction they want a solution, and it won't be the first textbook or teacher to first show you the wrong path, let you tremble, and then show you the right path.
The getCategory method doesn't always return (because of the if statement). Also, not sure about the height in if statement. Add another return invalid at the end of the method.
char getCategory(float height,float weight)
{
char invalid;
if(height<=0 || weight<=0)
return invalid;
return 0
}
you need to (very carefully) pore over your textbook to ascertain the multitude of errors in the above code.
1, your test in getCategory will almost certainly not do what you want it to do.
2, you ARE returning invalid in some cases (but not all, see #1). However, there is no way to know that as invalid has no known value.
3. in other cases, getCategory returns no value at all
You're defining a variable named invalid. Its contents are undefined (it could be anything from -128 to 127). When you return this variable you're returning anything; do you want to assign something to the invalid variable before you return it? e.g.
char invalid;
invalid = 'i';
if ( ... ) {
return invalid;
} else {
return 0;
}
What does invalid should be mapped to? You should have a convention like this:
char invalid_category = '?';
or perhaps:
#define INVALID_CATEGORY '?'
This is better defined outside of the getCategory function so that the calling code can access it.
Also it isn't evident what your code returns when valid arguments are passed to it.
By the way, in your function getCategory, you have a variable that is not used nor declared - starvation. Where does that come from? I doubt that is a global variable.
Also, the variable bmirange does not make sense nor would it compile
bmirange=[weight/(height*height)];
as you can see that is a left hand side expression (LHS) but you have used an array subscript operators on the right hand side of expression (RHS). That is an illegal statement!
What was your intention there? Was that meant to be a pair of parenthesis?
Can you confirm this?
A lot of the answers are confusing because the OP did not make themselves clear on what is the error nor an explanation as to what is going on which is leading others to end up with code posted that does not satisfy the OP.
Hope this helps,
Best regards,
Tom.

Resources