How many times called the function calculate? İn C - c

I have one question.
I want to write a program with fibonacci, but i have a problem.
"Every time the function is called from the main function, it should print out how many times it has been called"
I try add counter, but every time counter is 1. Thx

You should use the static variable or you can pass the count variable for each call. The below one is for static variable case
#include<stdio.h>
int fib(int n)
{ static int count = 0;
count++;
printf("%d", count);
if (n <= 1)
return n;
return fib(n-1) + fib(n-2);
}
int main ()
{
int n = 9;
printf("%d", fib(n));
getchar();
return 0;
}

Your initial attempt of adding a counter and it always being 1 tells me that you're a beginner. One very important concept you will need to get a handle on is "scope". When you create a local variable in a function, the variable gets allocated from the stack each time the function is called and is considered "in scope" for the duration of the function until you return. When you return from the function, the memory allocated for the variable is released and is no longer considered "in scope". Without specifically telling the compiler that you want the variable to hang around (using the static keyword), you are not guaranteed to get the same chunk of memory, and even if you did get the same chunk of memory, it's very likely that some other function has used it and destroyed whatever value was there.
So to answer your question specifically, you should use the static keyword in the variable declaration for your counter such as static int counter = 0; with an initial value of 0.

Related

Weird output behavior with char array in C [duplicate]

This question already has answers here:
Return a pointer that points to a local variable [duplicate]
(3 answers)
Closed 2 years ago.
I have a function that returns char* when I print it with printf("%c", *(k+i)); on the main it prints;
0' 10101001 Q -> Q
but if I print with printf(" %c", *(k+i)); there are less problem.
If I print inside the tobinary function, output comes perfect like this;
1010.011010011011101001011110001101010011111101111100111 -> 111011
What Am I doing wrong? here is the code.
char *tobinary(double num) {
int length = 62;
char bin[length];
int intpart = (int)num;
double decpart = 1000*(num - intpart);
int i = 0;
while (intpart!=0) {
if(intpart%2 == 1) bin[3-i] = '1';
else bin[3-i] = '0';
intpart /= 2;
i++;
}
bin[i++] = '.';
while (i <= length) {
decpart *= 2;
if (decpart >= 1000) {
bin[i] = '1';
decpart -= 1000;
}
else bin[i] = '0';
i++;
}
char *k = bin;
return k;
}
int main(int argc, char **argv) {
char *k = tobinary(10.413);
for(int i = 0; i <= 62; ++i) {
printf("%c", *(k+i));
if (i==56) printf(" -> ");
}
}
When you declare a local variable in a function, like this
char *tobinary(double num) {
int length = 62;
char bin[length];
/* ... */
}
it is stored in a special memory area called stack. Whenever a function func() is called, the CPU saves there some useful data such as the address of the calling function where the execution will be restored after func() returns, along with the parameters of func() and, as I wrote above, any local variable declared in it.
All this data is stacked with a LIFO criteria (Last In, First Out), so that when function returns a special pointer (stack pointer) is changed to point back to the data regarding the calling function. func()'s data is still there, but it can be overwritten whenever another function is called or other local variables are declared by caller(). Please note that it is compliant with the fact that local variables have a lifetime limited to the function in which they are declared.
That's what happen in your scenario. Since the execution goes on, your bin[] array is not guaranted to stay "safe":
int i is declared in the for-loop section
printf() is called
This is what corrupts "your" data (I used double quotes because it is not yours anymore).
Whenever you need to return data manipulated by a function, you have three options:
Declare the array outside it and pass it to the function after changing its prototype: int tobinary(char *arr, unsigned int arrsize, double num);. In this way the function can modify the data passed by the caller (changing at most arrsize characters). The return value can become an error code; something like 0 on success and -1 on failure.
Dynamically allocate the array inside your function using malloc(). In this case freeing the memory (with free()) is responsability of the caller function.
Declare the array in your function as static. This qualifier, in fact, tells the compiler that the lifetime of the variable is the whole life of the program, and a different specific memory area is used to store it instead of the stack. Be aware that in this case your function won't be thread safe anymore (different thread accessing the same memory area would lead to bizarre results).
bin is character array inside your function.
It is not static, so when you return a pointer to it, it is not guaranteed to keep the same value.
Either change it to static or return a memory you allocate and the caller will need to free that memory.

How to have a global variable in C that increments when used by any function

I am attempting to have a gobal counter the can can used by any function in the program. Is this possible?
int* count;
main(){
*count = 0;
}
void incrementCount(){
++*count;
}
int getCount(){
return *count;
}
If not possible how can I do something similar?
No need to take a pointer. Take a Variable like
int count;
If you are going to use it in a single file better to declare it static.
A much better approach would be using the getter and setter functions instead of updating global variable everywhere
I am attempting to have a gobal counter the can can used by any function in the program. Is this possible?
Yes, even though it's not a good thing to use global variable.
All you need to do is to declare the function in global scope. You should also initialise it in main before any function call.
int count;
int main()
{
count = 0;
incrementCount();
...
}
There is no need to use pointer in your case. And it's wrong as well, because you have not allocate any memory for that pointer.
Firstly there are few issues in the shared code sample. Here
int* count; /* count is pointer i.e you need to make count to hold or point to some valid memory location */
count is of int pointer type. And here
*count = 0; /* de-referencing uninitiated pointer */
you are trying to de-reference count which has not valid memory. It causes segmentation fault. Before de-referencing you need to allocate memory. for e.g
count = malloc(sizeof(*count));
/* error handling of malloc return value */
*count = 0;
I am attempting to have a gobal counter the can can used by any
function in the program ?
You can do the same task without using pointer, try using static if use having file scope. If possible avoid using global variable.
You can just declare the variable as integer (not pointer).
You can have a global getter and setter function. Also initialize the global variable before any function call, best will be in Main().
first, you can't do
*count = 0;
if you don't have initialised your pointer, it means refrenced to a
variable like:
count = &x;
Then, if you want that variable is shared and the value is always
updated between methods you can simply declare the variable as
"static",
#include <stdio.h>
static int count;
main(){
printf("%d",count);
}
void incrementCount(){
++count;
}
int getCount(){
return count;
}

The last value of an array of array of ints overrides all other values

I'm trying to store 4 arrays in an array, and for some reason, the last value keeps overriding the previous three values. For example, if 123; 456; 789; 987 were inputted into the code below, ipadr[0] - ipadr[4] would all only store 123. I've tested to make sure that numConvert() is working, and within numConvert, 4 different arrays of ints are returned, but only numConvert(d) is the ipadr array (stored 4 times).
Also, is my syntax / code correct in order for this function to return ipadr as an array of arrays (int**)? Why do you need to make it static int* when initializing the array?
I'm new to C and this has been really frustrating me. Any help would be incredibly appreciated. Thank you in advance!!
int** ipConvert(int a, int b, int c, int d){
static int* ipadr[4];
ipadr[0]=numConvert(a);
ipadr[1]=numConvert(b);
ipadr[2]=numConvert(c);
ipadr[3]=numConvert(d);
return ipadr;
}
numConvert code:
int* numConvert(int dec) {
static int hold[8];
...
return hold;
}
The hold array is indeed overwritten after each call to numConvert, because it is a static area of 8 int.
Better use dynamic allocation with malloc, and have that function allocate 8 ints.
int* numConvert(int dec) {
int *hold = (int *)malloc(sizeof(int) * 8); // C++ need cast!
int x = dec;
for(int y=7;y>=0;y--){
if(x%2==0 || x==0){
hold[y]=0;
}
else{
hold[y]=1;
}
x=x/2;
}
printf("\ntest loop: ");
for(int i=0;i<8;i++){
printf("%i", hold[i]);
}
printf("\n");
return hold;
}
then the returned values will have to be freed, after you don't need them anymore.
As for static, this answer explains it in details.
Every time you write something in hold then return it, you basically overwrite the previous value. There is single instance of hold not multiple as you may be thinking.
static keyword you have used without knowing the full functionality. It is not the same as automatic storage duration.
int* numConvert(int dec) {
int *hold = malloc(sizeof *hold *8);
if( hold == NULL){
fprintf(stderr,"Error in malloc");
exit(1);
}
int x = dec;
....
....
return hold;
}
Free the dynamically allocated memory when you are done working with it.
What have we done here?
Dynamically allocated memory has lifetime beyond the scope of the function. So just like the static one it stays alive. But with contrary to the static variable each time a new chunk of memory is allocated. And for that we are not overwriting anything, which was the primary problem in your case.
One thing more..
hold is of automatic storage duration meaning every time we exit the function the hold is deallocated and then again when we call it we get to have a local variable named hold. So in each we get different instance. And that's why we return the address contained in hold. This memory whose address hold contains has lifetime beyond the scope of the function. So it stays unlike the local variable hold and we store this address in other function.
Declare your hold variable as instance variable rather then static variable like
int* numConvert(int dec) {
int hold[8];

When is memory deallocated in c?

I am trying to find out when memory used for variables in c is freed. As an example, when would the integer i be freed in the following code snippet?
int function()
{
int i = 1;
// do some things
return 0;
}
In C, as in all other languages, lexically scoped variables, such as i here, are only valid within their scopes -- the scope of i is from its declaration through the closing brace of the function. When exactly they are freed is often not specified, but in practical C implementations local variables are allocated on the call stack and their memory is reused once the function returns.
Consider something like
int function()
{
int i; // beginning of i's scope
{
int j; // beginning of j's scope
...
} // end of j's scope
{
int k; // beginning of k's scope
...
} // end of k's scope
return 0; // all locals of the function are deallocated by the time it is exited
} // end of i's scope
Scope determines when the variables can be accessed by name and, for local (auto) variables, when their content can be validly accessed (e.g., if you set a pointer to the address of a local variable, dereferencing the pointer outside the variable's scope is undefined behavior). Deallocation is a somewhat different matter ... most implementations won't do anything at the end of j or k's scope to "deallocate" them, although they will likely reuse the same memory for both variables. When function returns, most implementations will "pop" all locals off the stack, along with the return address, by a single decrement of the stack pointer, in effect "deallocating" their memory ... although the memory is still right there on the stack, ready to be "allocated" to the next function that is called.
Note that the terminology of your question is somewhat confused ... variables have scope, but it's memory, not variables, that is allocated and deallocated. Some variables may not even have any memory allocated for them if, for instance, they are constants or are never used in the program. And only the memory for local variables is allocated or freed as described above ... the memory for static and file scope variables is never freed, and only allocated when the program is loaded. And there is other memory -- heap memory -- that is explicitly allocated and freed by your program (via calls to malloc/realloc/calloc/strdup/free etc.). But although heap memory can be referenced by pointer variables, the memory for the pointer variables themselves consists just of the reference (memory address), with the variables having either local or static/file scope.
It will be freed when it goes out of scope. Since it has function scope, this will happen when the function returns.
i is allocated on the stack. It is freed when return is executed.
Automatic variables are local to a scope in C:
A scope is basically marked by '{' '}' so when you are inside a {} pair you are inside a scope. Of course scopes can be nested.
This is why in older C standard the local variables had to be defined at the top of a scope because it made writing the C compiler easier (the compiler would see a '{' and then all the variables and then statements) so it knew the variables it had to deal with. This changed in C99 (I think?) and later on where you can define variables anywhere in between statements.
This can be quite helpful of course:
int foo()
{
int k = 0; /* inside the scope of foo() function */
for(; k < 10; k++) { /* don't need k = 0; here we set it to zero earlier */
int i = 1; /* initialize inside the scope of the for loop */
i = i * 2; /* do something with it */
printf ("k = %d, i = %d\n", k, i);
}
#if 0
printf ("i = %d\n", i); /* would cause an unknown identifier error
* because i would be out of scope, if you changed
* #if 0 to #if 1
*/
#endif
return 0;
}
int main()
{
foo();
foo();
return 0;
}
Notice that i = 2 all the time for the iterations of the loop in foo()
A more fun thing to see is how the keyword static modifies the persistence of the variable.
int bar()
{
int k = 0; /* inside the scope of bar() function */
for(; k < 10; k++) { /* don't need k = 0; here we set it to zero earlier */
static int i = 1; /* initialize inside the scope of the for loop */
i = i * 2; /* do something with it */
printf ("k = %d, i = %d\n", k, i);
}
#if 0
printf ("i = %d\n", i); /* would cause an unknown identifier error
* because i would be out of scope, if you changed
* #if 0 to #if 1
*/
#endif
return 0;
}
int main()
{
foo();
foo();
return 0;
}
Note the changes and note how a static variable is treated.
What would happen to the for loop if you put the keyword static in front of int k = 0; ?
Interesting uses
C macros are very useful. Sometimes you want to define a complicated local macro rather than a function for speed and overall simplicity. In a project I wanted to manipulate large bit maps, but using functions to perform 'and' 'or' 'xor' operations was a bit of a pain. The size of bitmaps was fixed so I created some macros:
#define BMPOR(m1, m2) do { \
int j; \
for (j = 0; j < sizeof(bitmap_t); j++ ) \
((char *)(m1))[j] |= ((char *)(m2))[j]; \
} while (0)
the do { } while(0) is a fun trick to let a scoped block be attached to if/for/while etc. without an issue, the block executes exactly once (since the while is checked at the END of the block), and when compiler sees while(0) it just removes the loop; and of course this lets you put a semi-colon at the end so IDEs and you (later) don't get confused about what it is.
The macro above was used as under:
int foo()
{
bitmap_t map_a = some_map(), map_b = some_other_map();
BITOR(map_a, map_b); /* or map_a and map_b and put the results in map_a */
}
here the do {} while(0) allowed a local scope with a local variable j, a for loop and anything else that I might have needed.
Variable gets deallocated when the variable gets out of scope.In your code variable i will get deallocated after return 0 statement is executed.
You can find more on variable scope here

Variable reuse in C

The code I'm looking at is this:
for (i = 0; i < linesToFree; ++i ){
printf("Parsing line[%d]\n", i);
memset( &line, 0x00, 65 );
strcpy( line, lines[i] );
//get Number of words:
int numWords = 0;
tok = strtok(line , " \t");
while (tok != NULL) {
++numWords;
printf("Number of words is: %d\n", numWords);
println(tok);
tok = strtok(NULL, " \t");
}
}
My question centers around the use of numWords. Does the runtime system reuse this variable or does it allocate a new int every time it runs through the for loop? If you're wondering why I'm asking this, I'm a Java programmer by trade who wants to get into HPC and am therefore trying to learn C. Typically I know you want to avoid code like this, so this question is really exploratory.
I'm aware the answer is probably reliant upon the compiler... I'm looking for a deeper explanation than that. Assume the compiler of your choice.
Your conception about how this works in Java might be misinformed - Java doesn't "allocate" a new int every time through a loop like that either. Primitive type variables like int aren't allocated on the Java heap, and the compiler will reuse the same local storage for each loop iteration.
On the other hand, if you call new anything in Java every time through a loop, then yes, a new object will be allocated every time. However, you're not doing that in this case. C also won't allocate anything from the heap unless you call malloc or similar (or in C++, new).
Please note the difference between automatic and dynamic memory allocation. In Java only the latter exists.
This is automatic allocation:
int numWords = 0;
This is dynamic allocation:
int *pNumWords = malloc(sizeof(int));
*pNumWords = 0;
The dynamic allocation in C only happens explicitly (when you call malloc or its derivatives).
In your code, only the value is set to your variable, no new one is allocated.
From a performance standpoint, it's not going to matter. (Variables map to registers or memory locations, so it has to be reused.)
From a logical standpoint, yes, it will be reused because you declared it outside the loop.
From a logical standpoint:
numWords will not be reused in the outer loop because it is declared inside it.
numWords will be reused in the inner loop because it isn't declared inside.
This is what is called "block", "automatic" or "local" scope in C. It is a form of lexical scoping, i.e., a name refers to its local environment. In C, it is top down, meaning that it happens as the file is parsed and compiled and visible only after defined in the program.
When the variable goes out of scope, the lexical name is no longer valid (visible) and the memory may be reused.
The variable is declared in a local scope or a block defined by curly braces { /* block */ }. This defines a whole group of C and C99 idioms, such as:
for(int i=0; i<10; ++i){ // C99 only. int i is local to the loop
// do something with i
} // i goes out of scope here...
There are subtleties, such as:
int x = 5;
int y = x + 10; // this works
int x = y + 10;
int y = 5; // compiler error
and:
int g; // static by default and init to 0
extern int x; // defined and allocated elsewhere - resolved by the linker
int main (int argc, const char * argv[])
{
int j=0; // automatic by default
while (++j<=2) {
int i=1,j=22,k=3; // j from outer scope is lexically redefined
for (int i=0; i<10; i++){
int j=i+10,k=0;
k++; // k will always be 1 when printed below
printf("INNER: i=%i, j=%i, k=%i\n",i,j,k);
}
printf("MIDDLE: i=%i, j=%i, k=%i\n",i,j,k); // prints middle j
}
// printf("i=%i, j=%i, k=%i\n",i,j,k); compiler error
return 0;
}
There are idiosyncrasies:
In K&R C, ANSI C89, and Visual Studio, All variables must be declared at the beginning of the function or compound statement (i.e., before the first statement)
In gcc, Variables may be declared anywhere in the function or compound statement and is only visible from that point on.
In C99 and C++, Loop variables may be declared in for statement and are visible until end of loop body.
In a loop block, the allocation is performed ONCE and the RH assignment (if any) is performed each time.
In the particular example you posted, you enquired about int numWords = 0; and if a new int is allocated each time through the loop. No, there is only one int allocated in a loop block, but the right hand side of the = is executed every time. This can be demonstrated so:
#include <stdio.h>
#include <time.h>
#include <unistd.h>
volatile time_t ti(void){
return time(NULL);
}
void t1(void){
time_t t1;
for(int i=0; i<=10; i++){
time_t t2=ti(); // The allocation once, the assignment every time
sleep(1);
printf("t1=%ld:%p t2=%ld:%p\n",t1,(void *)&t1,t2,(void *)&t2);
}
}
Compile that with any gcc (clang, eclipse, etc) compatible compiler with optimizations off (-O0) or on. The address of t2 will always be the same.
Now compare with a recursive function:
int factorial(int n) {
if(n <= 1)
return 1;
printf("n=%i:%p\n",n,(void *)&n);
return n * factorial(n - 1);
}
The address of n will be different each time because a new automatic n is allocated with each recursive call.
Compare with an iterative version of factorial forced to used a loop-block allocation:
int fac2(int num) {
int r=0; // needed because 'result' goes out of scope
for (unsigned int i=1; i<=num; i++) {
int result=result*i; // only RH is executed after the first time through
r=result;
printf("result=%i:%p\n",result,(void *)&result); // address is always the same
}
return r;
}
In conclusion, you asked about int numWords = 0; inside the for loop. The variable is reused in this example.
The way the code is written, the programmer is relying on the RH of int numWords = 0; after the first to be executed and resetting the variable to 0 for use in the while loop that follows.
The scope of the numWords variable is inside the for loop. Just as Java, you can only use the variable inside the loop, so theoretically its memory would have to be freed on exit - since it is also on the stack in your case.
Any good compiler however would use the same memory and simply re-set the variable to 0 on each iteration.
If you were using a class instead of an int, you would see the destructor being called every time the for loops.
Even consider this:
class A;
A* pA = new A;
delete pA;
pA = new A;
The two objects created here will probably reside at the same memory.
It will be allocated every time through the loop (the compiler can optimize out that allocation)
for (i = 0; i < 100; i++) {
int n = 0;
printf("%d : %p\n", i, (void*)&n);
}
No guarantees all 100 lines will have the same address (though probably they will).
Edit: The C99 Standard, in 6.2.4/5 says: "[the object] lifetime extends from entry into the block with which it is associated until execution of that block ends in any way." and, in 6.8.5/5, it says that the body of a for statement is in fact a block ... so the paragraph 6.2.4/5 applies.

Resources