Indirect variables access in C not C++ - c

is it possible to access variable value through other variable, as below
char var[30];
char buffer[30];
strcpy(buffer, "ABC");
/*variable var is holding the "buffer" variable name as string*/
strcpy(var,"buffer")
is there a way to access the buffer variable value "ABC", through variable var. ?

Not in any practical way in C, and you don't really want to anyway. Tying your program logic to the names of your variables is a horrible idea. Typically I see people attempt this when what they really need is some sort of collection type (and array, a map, whatever).
How about filling us in on the problem you are trying to solve with this?
Per your comment:
I need to have dynamic debug messages, I have a file which contain each function variables that I want to print.
Use stringification in a macro:
#define str(s) #s
int main() {
int bar;
str(bar) /* replaced by "bar" */
}

Not without significant boiler plate code. Variable names are eliminated at compile-time.
In theory, you could store a map from variable names to a pointer to a variable.

No, you can't. If you want indirect access, then declare a pointer and assign var to it.
char *forVar = var;
// Now you can access/modify via [] operator.

You can try using a union
For example:
union example {
char var[40];
char buffer[40];
} e1;
strcpy(e1.var, "ABC");
printf("%s is same as %s", e1.var, e1.buffer);

So basically you want to log some variables when they are written to/read from/passed to functions etc?
Doing this with compiled C is difficult, as mentioned, especially if you are optimising your executable (-0n on the compile statement), in which case some of the variables can disappear completely, or get re-used by other variables.
Using GDB
Having said that, I know gdb can log variable access and that sort of stuff. If you were to write a python script (see http://sourceware.org/gdb/onlinedocs/gdb/Python.html), you should be able to write a script to log variable content.
See this question for more: Do specific action when certain breakpoint hits in gdb
On demand only, using pre-compiler scripting
Alternatively, if you just wanted to do it on demand, you'd be better off using a pre-processing script to add in custom macro's or similar, using a csv file as input:
for each line in CSV:
read variable_name, file_name, variable_type
find all occurrences of variable_name in file_name
for each occurrence
insert printf(....)
On demand only, using macros
Good luck. There isn't a nice way to do it, because you'd generally need some sort of lookup, and you'd need a way of selectively outputting variables to your print function. In some cases you could do something like:
static char _LOGGED_VAR_001 = 'z';
static char _LOGGED_VAR_002 = 'z';
#define cMyVar _LOGGED_VAR_001
#define LOG_ALL_VARS() printf("Vals: %c, %c", _LOGGED_VAR_001, _LOGGED_VAR_002)
void myFunc()
{
char cMyVar; // Gets macro'd to _LOGGED_VAR_001 with LOCAL scope
cMyVar = 'a'; // LOCAL scope _LOGGED_VAR_001 becomes 'a'
LOG_ALL_VARS(); // At this point you print out the LOCAL _LOGGED_VAR_001
// and the global _LOGGED_VAR_002
}
You would get Vals: a, z
This is pretty ugly, would only work for variables with local scope, messes round with memory consumption, could be error prone and is generally a bad idea.
On demand, heap/stack dump
If you have enough storage, you could dump all your memory on demand to a file. This probably wouldn't be very portable, depending on how it was done. I'm not sure how to do it though, in a reliable manner.
Recommendation
Use GDB for design-time diagnostics. It's what it's designed for :)
For (e.g.) analysing released code (automated bug reports), a full dump and then analysis at will might be relevant.

Related

static analysis - how to simply detect assignment statements in C

I want to write a script that verifies there are no assignments of certain global variables. Say I have all my global variables initialized in files specifically for that, and that I don't want to pass these files into my script.
For example, I want to verify there are no assignments in any of my global variables that start with X_.
int var1 = 5; // that is fine
int X_global_var1 = 10; // error
How do I detect that without reinventing the wheel? is there an easy way in Python?
It is not simple as it sounds because there might be more cases like == and if the variable is a pointer to data then *X_global_var1 = 2; is legal too..
For encountering code comments for example, I use Comment Parser python package, with a C language flag and it works great. Looking for something similar for assignments.

Is it possible to get a function name without invoking it?

How can i get a function's name without calling/invoking it, or is that even possible ?
I have an array of sorting functions, my goal is to be able to list the name of each one, dynamically, without having to invoke any.
After searching on the web, i couldn't find any solution that doesn't require the function being invoked and uses __FUNCTION__ or __func__.
The array of functions that is use:
// Pointer to functions
char *(*srtFunc[])(int *, int) = {selection, bubble, recursiveBubble, insertion, recursiveInsertion};
More information about what I want to achieve with this:
I want to loop over each function in the given array, create a file with the name of the function, invoke the function 100 times with different arguments each time, and print the time spent by the function each time in its dedicated file, redo for the remaining functions.
Unfortunately, not easily. C is not built for introspection and doesn't have features like this-- the name of function foo and the call to function foo are compiled down to just some jump and call instructions in the output; the actual name "foo" is essentially a convenience for you when programming and disappears in the compiled output.
The macro __FUNCTION__ is a preprocessor macro-- and as you note it only works within a function, because all it does it tell the preprocessor (as its churning through the text) hey, as you're scanning this token just drop in the name of the function you're currently scanning and then continue on. It's very "dumb" and is upstream of even the compiler.
There are various ways to get the effective result you want here, including most simply just manually building a table of string literals that have the same names as your functions. You can do this in fairly clean ways (see #nielsen's answer for a useful snippet) using macros. But the preprocessor/compiler can't help you derive or enforce a table from the actual functions so you will always have some risk of an issue at runtime when you make changes to it. Unfortunately C just doesn't have the capability for the kind of elegance you're looking for in this design.
You may be able to do something with smart preprocessor tricks, but your code would be difficult to read. I think I would go for the really low-tech solution here and just add an array of the function names matching the array of function pointers:
#define ARRAY_SIZE(A) (sizeof(A)/sizeof(A[0]))
// Pointer to functions
char *(*srtFunc[])(int *, int) = {selection, bubble, recursiveBubble, insertion, recursiveInsertion};
const char *srtFuncNames[] = {"selection", "bubble", "recursiveBubble", "insertion", "recursiveInsertion"};
_Static_assert(ARRAY_SIZE(srtFuncNames)==ARRAY_SIZE(srtFunc), "Function table and names out of synch!");
Having the two definitions just after each other makes it easy to keep them synchronized and the code is easy to read. The _Static_assert (available from C11) will help remembering to add new names as new functions are added.
Alternatively, a structure can be defined holding a function pointer and corresponding name. This can be initialized using a macro as follows:
typedef struct
{
char *(*srtFunc)(int *, int);
const char *srtName;
} sortMethod;
#define SORT_METHOD(S) {(S), #S}
sortMethod methods[] = {
SORT_METHOD(selection),
SORT_METHOD(bubble),
SORT_METHOD(recursiveBubble),
SORT_METHOD(insertion),
SORT_METHOD(recursiveInsertion)
};

Is it possible in C to create a file scope object whose address may not be computed?

What I want is to ensure that file scope variables (in my program) can not be modified from outside the file. So I declare them as 'static' to preclude external linkage. But I also want to make sure that this variable can not be modified via pointers.
I want something similar to the 'register' storage class, in that
the address of any part of an object declared with storage-class
specifier register cannot be computed, either explicitly (by use of
the unary & operator) or implicitly (by converting an array name to a
pointer).
but without the limitations of the 'register' keyword (can not be used on file scope variables, arrays declared as register can not be indexed).
That is,
<new-keyword> int array[SIZE] = {0};
int a = array[0]; /* should be valid */
int *p = array; /* should be INVALID */
p = &array[3]; /* should be INVALID */
What is the best way to go about achieving this goal?
Why do I desire such a feature?
The usage scenario is that this file will be modified by many people in the future even when I can not personally overview all modifications. I want to preclude as many potential bugs as possible. In this case I want to make sure that variables meant to be 'private' to the module will remain so without having to depend just on documentation and/or discipline
No, I don't think you can do so, at least not cleanly. But I also fail to understand your usage case fully.
If your object is static, nobody knows its name outside of your module. So nobody can use & to take its address.
If you need to expose it, and don't want other parts of the program modifying it, write a function that exposes it as a constant pointer:
static int array[SIZE];
const int * get_array(void)
{
return array;
}
Then compile with warnings. If somebody casts away the const, it's their problem.
Assuming you are concerned with security issues, here are a few things to consider:
The purpose of register keyword was to recommend the compiler to keep that variable in a register, as it will be intensively used. As the registers don't have a memory address, it is impossible to get it (although this wasn't the primary purpose of this keyword; it is merely a side-effect). As compilers got better at generating efficient code, this is not needed any more.
Even if you could make all objects in your code "addess-proof" (impossible to get their address), the program will still not be 100% safe. Those objects are still stored in memory, which is still visible. By analysing the binary files, using debuggers, analysing the memory map and so on, one could find out those memory addresses.
This is not a good practice. In order for someone to get the variable of an object in a module, that object must be global, which is bad. So you should worry about having global variables, not about their visibility. Here you can find more details about why is it bad to have variables in the global scope.
As a semi-solution to your "problem", you can declare them const static. This way they cannot be accessed from outside the module and if it happens, no one can change their value.

Local synonymous variable to non exact type

I'm a little bit new to C so I'm not familiar with how I would approach a solution to this issue. As you read on, you will notice its not critical that I find a solution, but it sure would be nice for this application and future reference. :)
I have a parameter int hello and I wan't to make a synonomous copy of not it.
f(int hello, structType* otherParam){
// I would like to have a synonom for (!hello)
}
My first thought was to make a local constant, but I'm not sure if there will be additional memory consumption. I'm building with GCC and I really don't know if it would recognize a constant of a parameter (before any modifications) as just a synonymous variable. I don't think so because the parameter could (even though it wont be) changed later on in that function, which would not effect the constant.
I then thought about making a local typedef, but I'm not sure exactly the syntax for doing so. I attempted the following:
typedef (!hello) hi;
However I get the following error.
D:/src-dir/file.c: In function 'f':
D:/src-dir/file.c: 00: error: expected identifier or '(' before '!' token
Any help is appreciated.
In general, in C, you want to write the code that most clearly expresses your intentions, and allow the optimiser to figure out the most efficient way to implement that.
In your example of a frequently-reused calculation, storing the result in a const-qualified variable is the most appropriate way to do this - something like the following:
void f(int hello)
{
const int non_hello = !hello;
/* code that uses non_hello frequently */
}
or more likely:
void x(structType *otherParam)
{
char * const d_name = otherParam->b->c->d->name;
/* code that uses d_name frequently */}
}
Note that such a const variable does not necessarily have to be allocated any memory (unless you take its address with & somewhere) - the optimiser might simply place it in a register (and bear in mind that even if it does get allocated memory, it will likely be stack memory).
Typedef defines an alias for a type, it's not what you want. So..
Just use !hello where you need it
Why would you need a "synonym" for a !hello ? Any programmer would instantly recognize !hello instead of looking for your clever trick for defining a "synonym".
Given:
f(int hello, structType* otherParam){
// I would like to have a synonom for (!hello)
}
The obvious, direct answer to what you have here would be:
f(int hello, structType *otherParam) {
int hi = !hello;
// ...
}
I would not expect to see any major (or probably even minor) effect on execution speed from this. Realistically, there probably isn't a lot of room for improvement in the execution speed.
There are certainly times something like this can make the code more readable. Also note, however, that when/if you modify the value of hello, the value of hi will not be modified to match (unless you add code to update it). It's rarely an issue, but something to remain aware of nonetheless.

Making C module variables accessible as read-only

I would like to give a module variable a read-only access for client modules.
Several solutions:
1. The most common one:
// module_a.c
static int a;
int get_a(void)
{
return a;
}
// module_a.h
int get_a(void);
This makes one function per variable to share, one function call (I am thinking both execution time and readability), and one copy for every read. Assuming no optimizing linker.
2. Another solution:
// module_a.c
static int _a;
const int * const a = &_a;
// module_a.h
extern const int * const a;
// client_module.c
int read_variable = *a;
*a = 5; // error: variable is read-only
I like that, besides the fact that the client needs to read the content of a pointer. Also, every read-only variable needs its extern const pointer to const.
3. A third solution, inspired by the second one, is to hide the variables behind a struct and an extern pointer to struct. The notation module_name->a is more readable in the client module, in my opinion.
4. I could create an inline definition for the get_a(void) function. It would still look like a function call in the client module, but the optimization should take place.
My questions:
Is there a best way to make variables modified in a module accessible as read-only in other modules? Best in what aspect?
Which solutions above would you accept or refuse to use, and why?
I am aware that this is microoptimization - I might not implement it - but I am still interested in the possibility, and above all in the knowing.
Concerning option #4, I'm not sure you can make it inline if the variable isn't accessible outside the implementation file. I wouldn't count options #2 and #3 as truly read-only. The pointer can have the constness cast away and be modified (const is just a compiler "warning", nothing concrete). Only option #1 is read-only because it returns a copy.
For speed identical to variable access, you can define an extern variable inside an inline function:
static inline int get_a(void)
{
extern int a_var;
return a_var;
}
This is simple and clear to read. The other options seem unnecessarily convoluted.
Edit: I'm assuming that you use prefixes for your names, since you write C. So it will actually be:
extern int my_project_a;
This prevents a client from accidentally making a variable with the same name. However, what if a client makes a variable with the same name on purpose? In this situation, you have already lost, because the client is either 1) actively trying to sabotage your library or 2) incompetent beyond reasonable accommodation. In situation #1, there is nothing you can do to stop the programmer. In situation #2, the program will be broken anyway.
Try running nm /lib/libc.so or equivalent on your system. You'll see that most libc implementations have several variables that are not defined in header files. On my system this includes things like __host_byaddr_cache. It's not the responsibility of the C library implementors to babysit me and prevent me from running:
extern void *__host_byaddr_cache;
__host_byaddr_cache = NULL;
If you start down the path of thinking that you have to force clients to treat your variable as read-only, you are heading down the path of fruitless paranoia. The static keyword is really just a convenience to keep objects out of the global namespace, it is not and never was a security measure to prevent external access.
The only way to enforce read-only variables is to manage the client code — either by sandboxing it in a VM or by algorithmically verifying that it can't modify your variable.
The most common one:
There's a reason why it's the most common one. It's the best one.
I don't regard the performance hit to be significant enough to be worth worrying about in most situations.

Resources