Methods and structs in C - c

I was trying to solve this old lab sheet-
http://csis.bits-pilani.ac.in/faculty/murali/dsa-10/labsheet3_sec4.pdf
So my question is I have to use this method -
int createMaze(Maze *pm, char *mazefilename)
This will enter values in the Maze.But since it is not returning the Maze how can I use it in this method-
Boolean findCheese(Maze m, int n, int posi, int posj, char
**path_so_far, int past_i, int past_j)
Also I cant call findCheese method from createMaze I have to call both of them from another driver.c file.SO is the definitions of the methods wrong or is there someway I can use Maze in both the methods?

In the document you linked to, it says:
Create a driver file maze.c for meeting the objectives of this problem.
This creates the Maze using createMaze. It then calls findCheese to determine the path.
The code will look something like:
Maze m;
createMaze(&m, "some file name");
findCheese(m, ... rest of the arguments ...);

Related

Eclipse CDT: How to generate header file from source file?

Eclipse IDE for C/C++ Developers
Version: 2018-12 (4.10.0)
Build id: 20181214-0600
Hello,
is there a way to auto generate a header (.h) from functions in a source (.c) file (plus keeping it up to date)? May be even a vice versa generator?
Example:
test.c
void print_val(int val) {
printf("Val: %i", val);
}
int add(int val1, int val2) {
return (val1 + val2);
}
Now I want to generate automaticly an header file
foo.h
/*
* foo.h
*
* Created on: 22.02.2019
*
*/
#ifndef FOO_H_
#define FOO_H_
void print_val(int val);
int add(int val1, int val2);
#endif /* FOO_H_ */
Also the header file should auto update if I change something in the function declaration (if I want, best with checkboxes what to update)...
Eclipse has a function that generates an empty .c from a .h file that is called "Implement Methods". The opposite does not exist in Eclipse, and for pretty good reasons.
Don't get me wrong. Sometimes you need to change a header file, but it would not necessarily be a good thing to do this automatically. At least not without some kind of directives. For instance, when you're coding tail recursive functions, it is very common to have an auxiliary function that should not be exposed. It could look something like this:
int sumArrayAux(int * array, size_t size, int currentSum) {
if(size == 0) return 0;
return sumArrayAux(array + 1, size - 1, *array);
}
int sumArray(int * array, size_t size) {
return sumArrayAux(array, size, 0);
}
In general, you would not want to expose the first function. The function sumArray is intended to be the interface.
Another example is if you have data structures that are not meant to be fiddled with, except via the api. You could for instance have this:
struct Matrix {
int * values;
size_t cols, rows;
};
And some functions:
void matrixMultiply(Matrix * A, Matrix * B, Matrix *destination) {
...
}
size_t numberOfColumns(Matrix * m) { return M->cols; }
size_t numberOfRows(Matrix * m) { return M->rows; }
Then you would probably want a .h that looks like this:
typedef struct Matrix Matrix;
void matrixMultiply(Matrix * A, Matrix * B, Matrix *destination);
size_t numberOfColumns(Matrix * m);
size_t numberOfRows(Matrix * m);
But in other cases, for instance if numberOfX function does not exist, it could make more sense to expose the whole structure of Matrix.
The point is that the header file is supposed to be the interface, and you should not change an interface without a good reason and careful consideration. In the best of worlds you should be supposed to do whatever changes to the .c file without affecting any of the files that includes the .h.
Furthermore, it's not uncommon to have several .c files to implement one single .h. Also, you may have preprocessor macros defined that would complicate such an automatic translation.
After seeing that it seems there is no functionality, I am doing it quick and dirty with a regular expression search and replace:
Close all other tabs
STRG + H
Choose File tab
In search field the regular expression: (?m)(?s) \{.*?\R\}\R
Click on "Resource in active editor"
Click Replace
Replace it with a semicolon ;
Use preview to look at the changes (just in case)
May be there is something like a macro recorder for Eclipse out to do it with one click??
When having to create headers for bad legacy code I followed Tick Tac Joe's answer with this addition:
If the code contains the opening curly brackets on a new line, this regex works:
(?s)\R\{\R.*?\R\}
regex-replace into:
;
If you have mixed code, use this pattern first, to possibly prevent wrong matches by Tick Tac Joe's pattern (due to if's brackets).
(I cannot comment due to reputation)

Wrapping of function in the same file

I need your suggestion to wrap my existing function.
I am from testing team I need to write unit test cases, so I don't want to depend on original definition so trying to write my own definiton.
Following is the source code which should not be changed.
source.c:
#include <stdio.h>
const char *getObjectName (int *anObject);
void func()
{
int *p;
getObjectName(p);
}
const char *getObjectName (int *anObject)
{
printf("i am in original\n");
}
From the above code I want to wrap getObjectName() function so that I can give my own definition.
I have googled a lot and tried following methods but didn't work out:
Method 1. using ld --wrap method
Method 2. using -DINTERCEPT
Method 3. using function pointer
I cannot use above 3 methods because calling function and called function are in same file.
So please suggest me any other methods to write my own defintion for getObjectName().

Error of mexfunction variables in an array of a structure variable

Recently, I tried to write mexfunctions using structure variables.
I watched the tutorial but got confused because of how the variable values are passed.
The following example (mexfunction_using_ex_wrong.m & mexfunction_using_ex_wrong.cpp) demonstrates how to fetch the variables passed from matlab in mexfunction.
However, in this case, the result is:
address i_c1=2067094464 i_c2=2067094464
i_c1=10 i_c2=10
address i_c1=1327990656 i_c2=2067100736
i_c1=2 i_c2=20
address i_c1=2067101056 i_c2=2067063424
i_c1=3 i_c2=30
As can be seen, the 1st element of the c1 & c2 array of a structure variable is accidentally the same.
But, in another example (mexfunction_using_ex_correct.m & mexfunction_using_ex_correct.cpp), the elements of array 1 (b1) and array 2(b2) of a structure variable are unrelated as I expect.
The result is:
address i_b1=1978456576 i_b2=1326968576
i_b1=1 i_b2=10
address i_b1=1978456584 i_b2=1326968584
i_b1=2 i_b2=20
address i_b1=1978456592 i_b2=1326968592
i_b1=3 i_b2=30
However, it's more common to use the 1st example in programming. so could anybody explain why in the 1st example the addresses of i_c1 & i_c2 are the same?
The following code is mexfunction_using_ex_wrong.m
clc
clear all
close all
mex mexfunction_using_ex_c_wrong.cpp;
a.b(1).c1=double(1);
a.b(2).c1=double(2);
a.b(3).c1=double(3);
a.b(1).c2=double(1);
a.b(2).c2=double(2);
a.b(3).c2=double(3);
mexfunction_using_ex_c_wrong(a);
The following code is mexfunction_using_ex_c_wrong.cpp
#include "mex.h"
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
int i, j, k;
double *i_c1;
double *i_c2;
// for struct variables(pointers) inside fcwcontext
mxArray *mx_b, *mx_c1, *mx_c2;
mx_b=mxGetField(prhs[0], 0, "b");
for(i = 0;i < 3;i=i+1)
{
mx_c1=mxGetField(mx_b, i, "c1");
mx_c2=mxGetField(mx_b, i, "c2");
i_c1=mxGetPr(mx_c1);
i_c2=mxGetPr(mx_c2);
*i_c2=(*i_c2)*10;
printf("address i_c1=%d i_c2=%d\n", i_c1, i_c2);
printf(" i_c1=%g i_c2=%g\n", *i_c1, *i_c2);
}
}
The following code is mexfunction_using_ex_c_correct.m
clc
clear all
close all
mex mexfunction_using_ex_correct.cpp;
a.b1(1)=double(1);
a.b1(2)=double(2);
a.b1(3)=double(3);
a.b2(1)=double(1);
a.b2(2)=double(2);
a.b2(3)=double(3);
mexfunction_using_ex_correct(a);
The following code is mexfunction_using_ex_c_correct.cpp
#include "mex.h"
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
int i, j, k;
double *i_b1;
double *i_b2;
mxArray *mx_b1, *mx_b2;
mx_b1=mxGetField(prhs[0], 0, "b1");
mx_b2=mxGetField(prhs[0], 0, "b2");
for(i = 0;i < 3;i=i+1)
{
i_b1=mxGetPr(mx_b1);
i_b2=mxGetPr(mx_b2);
i_b2[i]=i_b2[i]*10;
printf("address i_b1=%d i_b2=%d\n", &i_b1[i], &i_b2[i]);
printf(" i_b1=%g i_b2=%g\n", i_b1[i], i_b2[i]);
}
}
The addresses are not "accidentally the same" - they're intentionally the same, due to MATLAB's internal copy-on-write optimisations. If you look at the MEX documentation, you'll see warnings scattered around...
Do not modify any prhs values in your MEX-file. Changing the data in these read-only mxArrays can produce undesired side effects.
...in various forms...
Note Inputs to a MEX-file are constant read-only mxArrays. Do not modify the inputs. Using mxSetCell* or mxSetField* functions to modify the cells or fields of a MATLABĀ® argument causes unpredictable results.
...trying to make it very clear that you should absolutely not modify anything you recieve as an input. By calling mxGetPr() on input data and writing back to that pointer as you do with i_b2 and i_c2, you're getting right into that "unpredictable results" territory - if you look at a.b(1).c1 in the MATLAB workspace after the call, it'll really be 10 even though you "only" changed c2.
From MEX, you're looking at the raw data storage without any knowledge of, or access to, MATLAB's internal housekeeping, so the only safe way to modify anything is to use the mxCreate* or mxDuplicate* functions to get your own safe arrays you can then do whatever you want with, and pass back to MATLAB via plhs.
That said, I will admit to having abused in-place modification for a significant performance gain in one instance where I could guarantee my data was unique and unshared, but it's at best unsupported and at worst downright perilous.

Is it possible to exchange a C function implementation at run time?

I have implemented a facade pattern that uses C functions underneath and I would like to test it properly.
I do not really have control over these C functions. They are implemented in a header. Right now I #ifdef to use the real headers in production and my mock headers in tests. Is there a way in C to exchange the C functions at runtime by overwriting the C function address or something? I would like to get rid of the #ifdef in my code.
To expand on Bart's answer, consider the following trivial example.
#include <stdio.h>
#include <stdlib.h>
int (*functionPtr)(const char *format, ...);
int myPrintf(const char *fmt, ...)
{
char *tmpFmt = strdup(fmt);
int i;
for (i=0; i<strlen(tmpFmt); i++)
tmpFmt[i] = toupper(tmpFmt[i]);
// notice - we only print an upper case version of the format
// we totally disregard all but the first parameter to the function
printf(tmpFmt);
free(tmpFmt);
}
int main()
{
functionPtr = printf;
functionPtr("Hello world! - %d\n", 2013);
functionPtr = myPrintf;
functionPtr("Hello world! - %d\n", 2013);
return 0;
}
Output
Hello World! - 2013
HELLO WORLD! - %D
It is strange that you even need an ifdef-selected header. The code-to-test and your mocks should have the exact same function signatures in order to be a correct mock of the module-to-test. The only thing that then changes between a production-compilation and a test-compilation would be which .o files you give to the linker.
It is possible With Typemock Isolator++ without creating unnecessary new levels of indirection. It can be done inside the test without altering your production code. Consider the following example:
You have the Sum function in your code:
int Sum(int a, int b)
{
return a+b;
}
And you want to replace it with Sigma for your test:
int Sigma(int a, int b)
{
int sum = 0;
for( ; 0<a ; a--)
{
sum += b;
}
return sum;
}
In your test, mock Sum before using it:
WHEN_CALLED: call the method you want to fake.
ANY_VAL: specify the args values for which the mock will apply. in this case any 2 integers.
*DoStaticOrGlobalInstead: The alternative behavior you want for Sum.
In this example we call Sigma instead.
TEST_CLASS(C_Function_Tests)
{
public:
TEST_METHOD(Exchange_a_C_function_implementation_at_run_time_is_Possible)
{
void* context = NULL; //since Sum global it has no context
WHEN_CALLED(Sum (ANY_VAL(int), ANY_VAL(int))).DoStaticOrGlobalInstead(Sigma, context);
Assert::AreEqual(2, Sum(1,2));
}
};
*DoStaticOrGlobalInstead
It is possible to set other types of behaviors instead of calling an alternative method. You can throw an exception, return a value, ignore the method etc...
For instance:
TEST_METHOD(Alter_C_Function_Return_Value)
{
WHEN_CALLED(Sum (ANY_VAL(int), ANY_VAL(int))).Return(10);
Assert::AreEqual(10, Sum(1,2));
}
I don't think it's a good idea to overwrite functions at runtime. For one thing, the executable segment may be set as read-only and even if it wasn't you could end up stepping on another function's code if your assembly is too large.
I think you should create something like a function pointer collection for the one and the other set of implementations you want to use. Every time you want to call a function, you'll be calling from the selected function pointer collection. Having done that, you may also have proxy functions (that simply call from the selected set) to hide the function pointer syntax.

Keeping directory search results of ftw function

what I have to do is recursively get ".mp3" archives from a determined pre-specified directory and its subdirectories. I did not have a problem getting the mp3's and printing them on console. I am using the ftw function specified in http://www.gnu.org/software/libc/manual/html_node/Working-with-Directory-Trees.html#Working-with-Directory-Trees, its call-back function would look like this:
/* Call-back of ftw function*/
int filter_mp3s(const char *dir_name, const struct stat *status, int typeflag){
if (typeflag == FTW_D){
struct dirent **mp3list;
int num_archives;
int counter;
num_archives = scandir (dir_name, &mp3list, select_mp3_ext, alphasort);
/* print mp3 names */
if (num_archives > 0) for (counter = 0; counter <= num_archives - 1; counter++) printf("%s\n", mp3list[counter]->d_name);
}
return 0;
}
What I really want to do is put the names of the files into a GTK combo-box widget. Problem is, that function returns an int type and the function is not flexible with its parameters so I could "save" in something the entries. In other words, mp3's are found but I have no idea how I could keep the results in order to load them in the combo-box in other function. I do not want to use global variables...
I'm new into this, thanks in advance for your help.
If the callback doesn't have a customer argument (usually a void*) which appears to be the case, you will have to put found data into a global variable, which is unfortunate.
If that's a problem (i.e. you are in a multithreaded environment) you will have to implement your own version of recursive directory traversal using opendir interface. It's not difficult.

Resources