This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How can one grab a stack trace in C?
Hi,
I would like to know how to print the contents of the current program stack (using C language).
say for eg.
call_some_function()
{
...
...
print_stack_till_now();
return something;
}
call_some_other_function()
{
...
...
print_stack_till_now();
return something;
}
main()
{
print_stack_till_now();
call_some_function();
print_stack_till_now();
call_some_other_function();
print_stack_till_now();
return 0;
}
In the prev example (may be not an example exactly :)) when I call the print_stack_till_now() function I should be able to print the current stack built till that point (including the newer function call entries, return location, their arguments etc.)
Is such a function possible in C language (even inlined assembly). Please point me to the theory (or existing code would be even better) needed to write such a function.
In gdb we can use backtrace to look at the current stack, I'm looking for something similar. Why do I need this ?... just wanted to learn.
Thank you.
There's no portable way to do this for the simple reason that C by itself doesn't define the concept of a stack data structure. It's completely open to the implementation how it does automatic storage and returns from function calls.
That being said most implementations provide some kind of stack unwinding mechanism. For example GCC/glibc provides the runtime specific function backtrace
http://www.gnu.org/s/libc/manual/html_node/Backtraces.html
There are similar stack unwinders for other plattforms. And of course you can implement your own backtracing mechanisms through a global, thread local storage array (it can be static and must provide only enough entries for how many function calls are supported by the stack size), where at each function call the calling module (using C preprocessor __FILE__), the line (C preprocessor __LINE__) and the called function (some additional preprocessor magic) are placed.
Related
Here is a simple C recursive program.
void func(void)
{
func();
}
int main()
{
func();
return 0;
}
Does this program use the stack in every call of func()
If yes, What does it stores in stack?
its not a terribly big program, id suggest compiling it, and running it and checking if youll get a stack overflow, okay argh....
I just tested it:
with /Od it returned resulted in overflow
with /O2 it also resulted in overflow, returning 3221225725
Tested on compiler explorer MSVC V19. latest
--what does it store in the stack?
The instruction pointer / Program Counter.
How else would the program know where to return to?
--whether optimized or not, the only change was the size of the function,
it wont optimize the function away. Or, MSVC 19.latest wouldnt.
If you find a compiler that does, that would be great for those virtual function calls to non-nothingness, which i believe is one of the critiques against them.
C standard does not know anything about the stack. So generally speaking this question does not have an answer.
This function calls itself at the end of its execution. It is called tail recursion (very specific case) and most modern optimising compilers will optimise it to an infinitive loop (assuming optimisations enabled).
Most implementations use the stack. Recursive functions (except tail recursion ones) will create a new stack frame on every call.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
1.Why "main" in the C main() function identifier?
2.If main is an identifier then how does a program execution starts from main only.
main is a function, almost exactly like any other. It's named by an identifier, it gets called, it receives some arguments, it does something, it returns a value. That's pretty much the definition of a function. The designers of C were going for simplicity, so it made perfect sense to have the program's entry point be an ordinary function.
If you're an assembly language programmer, you may know that a program's entry point is simply an address, not a full-fledged function. But that's assembly language talk: C is a higher-level language.
As others have explained, there's some low-level startup code somewhere (typically written in assembler), that has a program's actual entry point, as jumped to when your program starts up. That startup code is the code that actually calls your main function.
I said that main is an ordinary function, and it mostly is, but it has three special properties not shared by other functions:
It's just about the only function that you ever write where you don't get to pick your own name, return value, and argument types -- those are all chosen for you (or, if you want to think of it that way, forced on you) by the language. For example, the return type just has to be int, because the language says so. You don't get to make it some other type just because you want to (although of course lots and lots of programmers make it void, and often get away with it).
main actually has two valid sets of arguments it can accept: either zero or two, namely int and char ** (traditionally named argc and argv).
As a very special exception, even through main returns int, you're allowed to not have a return statement, and the compiler will basically insert one for you, making main() return 0 by default.
C standard defines the main function as the program entry point. It is called from the startup code or the program loader.
BTW you can change it (I do not know why but if you want you can) - example for the baremetal ARM
startup:
/* Call the clock system intitialization function.*/
bl SystemInit
/* Call static constructors */
bl __libc_init_array
/* Call the application's entry point.*/
bl initCCMRAM
/* Here was the main call */
bl my_entry_point_function
LoopForever:
b LoopForever
and in the C code
int my_entry_point_function(void)
{
...
}
I'd like to be able to generically pass a function to a function in C. I've used C for a few years, and I'm aware of the barriers to implementing proper closures and higher-order functions. It's almost insurmountable.
I scoured StackOverflow to see what other sources had to say on the matter:
higher-order-functions-in-c
anonymous-functions-using-gcc-statement-expressions
is-there-a-way-to-do-currying-in-c
functional-programming-currying-in-c-issue-with-types
emulating-partial-function-application-in-c
fake-anonymous-functions-in-c
functional-programming-in-c-with-macro-higher-order-function-generators
higher-order-functions-in-c-as-a-syntactic-sugar-with-minimal-effort
...and none had a silver-bullet generic answer, outside of either using varargs or assembly. I have no bones with assembly, but if I can efficiently implement a feature in the host language, I usually attempt to.
Since I can't have HOF easily...
I'd love higher-order functions, but I'll settle for delegates in a pinch. I suspect that with something like the code below I could get a workable delegate implementation in C.
An implementation like this comes to mind:
enum FUN_TYPES {
GENERIC,
VOID_FUN,
INT_FUN,
UINT32_FUN,
FLOAT_FUN,
};
typedef struct delegate {
uint32 fun_type;
union function {
int (*int_fun)(int);
uint32 (*uint_fun)(uint);
float (*float_fun)(float);
/* ... etc. until all basic types/structs in the
program are accounted for. */
} function;
} delegate;
Usage Example:
void mapint(struct fun f, int arr[20]) {
int i = 0;
if(f.fun_type == INT_FUN) {
for(; i < 20; i++) {
arr[i] = f.function.int_fun(arr[i]);
}
}
}
Unfortunately, there are some obvious downsides to this approach to delegates:
No type checks, save those which you do yourself by checking the 'fun_type' field.
Type checks introduce extra conditionals into your code, making it messier and more branchy than before.
The number of (safe) possible permutations of the function is limited by the size of the 'fun_type' variable.
The enum and list of function pointer definitions would have to be machine generated. Anything else would border on insanity, save for trivial cases.
Going through ordinary C, sadly, is not as efficient as, say a mov -> call sequence, which could probably be done in assembly (with some difficulty).
Does anyone know of a better way to do something like delegates in C?
Note: The more portable and efficient, the better
Also, Note: I've heard of Don Clugston's very fast delegates for C++. However, I'm not interested in C++ solutions--just C .
You could add a void* argument to all your functions to allow for bound arguments, delegation, and the like. Unfortunately, you'd need to write wrappers for anything that dealt with external functions and function pointers.
There are two questions where I have investigated techniques for something similar providing slightly different versions of the basic technique. The downside of this is that you lose compile time checks since the argument lists are built at run time.
The first is my answer to the question of Is there a way to do currying in C. This approach uses a proxy function to invoke a function pointer and the arguments for the function.
The second is my answer to the question C Pass arguments as void-pointer-list to imported function from LoadLibrary().
The basic idea is to have a memory area that is then used to build an argument list and to then push that memory area onto the stack as part of the call to the function. The result is that the called function sees the memory area as a list of parameters.
In C the key is to define a struct which contains an array which is then used as the memory area. When the called function is invoked, the entire struct is passed by value which means that the arguments set into the array are then pushed onto the stack so that the called function sees not a struct value but rather a list of arguments.
With the answer to the curry question, the memory area contains a function pointer as well as one or more arguments, a kind of closure. The memory area is then handed to a proxy function which actually invokes the function with the arguments in the closure.
This works because the standard C function call pushes arguments onto the stack, calls the function and when the function returns the caller cleans up the stack because it knows what was actually pushed onto the stack.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What should main() return in C/C++?
#include<stdio.h>
int main()
{
return 0;
}
In the code snippet given above, where does the return 0 returned by main go? Or in other words which function called the main function in the beginning.
main is called by some startup function in the C runtime library. The C language standard says that returning from main is equivalent to calling the exit function, so most C runtimes look something like this:
void _start(void) /* Exact function signature may vary */
{
/* Platform-specifi startup (e.g. fetch argc and argv from the OS) */
...
int status = main(argc, argv);
exit(status);
/* Never reached */
}
The exit status gets passed back to the operating system, and then what happens from there is OS-dependent.
When you compile and link your program, the executable file format (e.g. PE or ELF) contains a start address, which is the virtual address at which execution begins. That function is typically part of the C runtime library (like the example _start above). That function has to end by calling a system call such as exit, since if it just returned, it would have nowhere to go to: it would just pop an address off the stack and jump to that location, which would be garbage.
Depending on how the OS loader initializes processes, the program arguments argc, argv, and other data (such as the environment) might either come in as function parameters (either through registers or the stack), or they might require system calls (e.g. GetCommandLine on Windows) to retrieve them. But dealing with all of that is the job of the C runtime, and unless you're explicitly going out of your way to avoid using the C runtime, you needn't worry about those details.
Your compiler targets a certain platform, which includes operating-system specific mechanisms for starting processes. Part of that platform specific code contains the return value of main. When you link your program into an executable, there is an OS-specific piece of binary code that your linker adds which takes care of calling main and reporting the return value back to the operating system.
The return value goes to the hosted environment. Typically, operating system calls main and gets exits status of the program.
where does the return 0 returned by main go? Or in other words which function called the main function in the beginning.
It is called by the C startup library, a stub function that is called (almost) directly by the kernel. For example, on Linux and OS X, it's a function named _start. It has the same signature as main() and the operating system itself uses its return value.
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
What is the best solution to replace a new memory allocator in an existing code?
I'm writing a library in C. I'd like to know if there is a way to divert every malloc() call my library makes to a different "augmented" testmalloc() function that I provide without (significantly) modifying my library. This question is inspired from p158 of Kernighan and Pike's "The Practice of Programming", where they say
Write a version of your storage allocator that intentionally fails early, to test your code for recovering from out-of-memory errors.
I am in a position where I could provide a wrapper mymalloc() and use that exclusively in my library. I suspect it will be necessary to use this freedom to avoid multiple symbol definitions during linking.
yeah. you should include the library at last, and use #define malloc mymalloc
example:
library.h:
void * myalloc(int);
#define malloc myalloc
source.c:
#include <stdlib.h>
int* i = malloc(4);
-> uses myalloc
I guess writing your own malloc:
char* malloc(size_t sz)
{
return (char*)0;
}
and then linking it in doesn't work here?
(Background note: You can usually replace a function in a library with another by linking it in first in the link step. This doesn't replace the calls in the library, so the library still uses its own function, but everything that needed a link to malloc from your own code when the linker gets to your version will use your version.)
If you cannot modify the code you can consider using __malloc_hook.
See (http://www.gnu.org/s/libc/manual/html_node/Hooks-for-Malloc.html)
in addition to Yossarian's answer, you can use malloc hooks, defined at least for the GNU C library.
It is even possible to write a malloc() implementation that can succeed or fail depending on a global. Unix linkers won't look for the real malloc function as it finds one in the object file(s). I do not know how this would behave on Windows.
void *malloc(size_t aSize)
{
if (gNextMallocShallFail)
{
gNextMallocShallFail = 0; //--- next call will succeed
return NULL;
}
else
{
return realloc(NULL, aSize);
}
}