A while ago I read the Debugging Windows Programs book, and one of the tricks that it talked about extensively was calling functions from the Visual C++ debugger (quick)watch window.
As luck would have it, I don't have a copy on hand and the little documentation that I could find about this is really really poor.
So how DO you call a member function in the watch window? What if the function lives in a DLL? What if it is part of a namespace? Can you pass non-trivial parameters?
Let's use this example: I want to call the size() method of QList<MyType>, where MyType is a custom type.
Thanks!
It works and is hugely useful. You can evaluate expressions in the watch window or open the quick watch window (ctrl-alt-Q -- a very handy shortcut to know). It will let you call most forms of member functions. The only times it commonly tends to fail is if you've got overloaded operators, eg with smart pointers. For a simple class without overloaded operators you should find it should work well. I think it should accept non-trivial parameters (though obviously it depends how non-trivial!) As well as calling functions that return values, you can also call functions that modify the object -- there's no constraint on only calling getter methods.
The other kind-of-obvious thing to remember is that all variables are evaluated in the local stack frame, so ensure the variable is visible from the current point in the stack.
I'd say just write list.size() in the watch window, where list is an instance of your QList, but I'm not sure this works for all classes
Are you sure that you can call methods of objects while debugging code in Visual Studio? Because I was never able to do so. The closest debugging features I know is to have a quick watch on objects (including local objects in the stack, navigating through the call stack), or compile and continue (I used it in VC6) allowing to change the code, recompile and continue debuging from the last statement...
Related
This question already has answers here:
What is the point of function pointers?
(18 answers)
Closed 4 years ago.
I hope its an extremely repetitive question. And my advance excuse to all the viewers who find it annoying.
Although I am bit experienced programmer, but I cannot justify the use of function pointer over direct call. Scenarios where I unable to find the differences are -
1) callbacks - same can be achieved by direct call.
2) Asynchronous or synchronous event handling - anyway event has to be identified, based on which element no. in function pointer array got updated. But the same can be also done via direct call.
3) In some post I had seen people commenting it is to be used when it is not known which function to call. I didn't get any proper justification for this.
I really appreciate if someone can explain me using above scenarios with practical and really simple realistic example.
Some more things function pointers are often used for:
Runtime polymorphism: You can define a structure that encapsulates a function pointer, or a pointer to a function table. This enables you to call the specified function at runtime, even for a type of client object that did not exist when your library was written. You can use this to implement multiple dispatch or something like the visitor design pattern in C. This is also how C++ classes and their virtual member functions were originally implemented under the hood.
Closures: These can be structures containing a function pointer and one or more of its arguments.
State Machines: Instead of a switch with a case for each state label, I’ve often found it convenient to give the handler for each state its own function. The current state is the function you’re in, the state transitions are tail-recursive calls, and the program variables are parameters. The state labels then become function pointers, which you might store in a table or return from a function.
Higher-Order Functions: Two examples from the C standard library are qsort() and btree(), which generalize the type of elements and the comparison function.
Low-Level Support: Shared-library loaders, for example, need this.
1) callbacks - same can be achieved by direct call.
Not true. For a direct call, the caller must know the function name and signature when the code is compiled, and can only ever call that one function. A callback is defined at runtime and can be changed dynamically, while the caller need only know the signature, not the name. Moreover each instance of an object may have a different callback, whereas with a direct call, all instances must call the same function.
2) Asynchronous or synchronous event handling - anyway event has to be
identified, based on which element no. in function pointer array got
updated. But the same can be also done via direct call.
Not sure what you mean, but an event handler is simply a kind of callback. The event may be identified by the caller and different call-back handlers called through pointers. Your point only stands if there is one event handler for all event types and the user is to be responsible for identification.
3) In some post I had seen people commenting it is to be used when it is not known which function to call. I didn't get any proper justification for this.
See (1) and (2) above. Often it is a means to hook platform independent third-party library code into a specific platform without having to deliver source-code or for system events that require user/application-defined handlers.
I would not sweat it however - if all your application requirements can be resolved without using a pointer to a function, then you don't need a pointer to a function. When you need one, you will probably know. You will most likely encounter it when you have to use an API that requires it before you ever implement an interface yourself that does. For example in the standard library the qsort() function requires a pointer to a function in order to define how two objects of arbitrary type are to be ordered - allowing qsort() to support any type of object - it is a way in C of making a function "polymorphic". C++ supports polymorphism directly, so there is often less need for explicit function-pointers in C++ - although internally polymorphism is implemented using function pointers in any case.
There is a concept in programming called DRY -- don't repeat yourself.
Suppose you have 121 buttons in your UI. Each one of them behaves much the same, except when you press the button, a different operation happens.
You can (A) use virtual inheritance to dispatch to the right operation (requiring a class per button), or (B) use a function pointer (or a std::function) stored in the class in order to call the right "on click" handler, or (C) have every single button be a distinct type.
A virtual function is implemented in every compiler I have examined as a complex table that, in the end, is a collection of function pointers.
So your choices are function pointers or generating 121 completely distinct buttons that happen to mostly behave the same.
In any situation where you want to decouple the caller and the called, you must use something akin to a function pointer. There are a ridiculous number of cases, from work queues to thread off tasks, callbacks, etc.
In tiny programs where everything is hard coded, hard coding every call can work. But hard coded stuff like this doesn't scale. When you want to update those 121 buttons each hand-implemented, knowing their points of customization is going to be ridiculously difficult. And they will fall out of sync.
And 121 is a modest number of buttons. What about an app with 10,000? And you want to update every button's behavior to handle touch-based input?
Even more, when you type erase, you can reduce binary size significantly. 121 copies of a class implementing a button is going to take more executable space than 1 class, each of which stores a function pointer or two.
Function pointers are but one type of "type erasure". Type erasure reduces binary size, provides clearer contracts between provider and consumer, and makes it easier to refactor behavior around the type erased data.
Without function pointers, how would you implement a function which calculates the integral of any real-valued function?
typedef double (*Function)(double);
double Integral(Function f, double a, double b);
1) callbacks - same can be achieved by direct call.
Not in all cases, since the caller may not know at compile-time what function must be called. For instance, this is typical in libraries since they cannot know in advance your code.
However, it can also happen in your own code: whenever you want to re-use partially a function, you can either:
Create several versions of that function, each calling a different function. Duplicates code, very bad maintenance. Good performance unless hit by code bloat.
Pass a function pointer (or callable in general in C++). Flexible, less code, performance might suffer in some cases.
Create a set of branches (if/switch chain), if you know in advance the set of possible functions to call. Rigid, but might be faster than a function pointer for small number of branches.
In C++, create a templated version. Same as the first case, but automated; so good maintenance. Code bloat might be an issue.
Factor out the common code so that callers can call whatever they need piece by piece. Sometimes this isn't possible/easy -- specially when parametrizing complex algorithms that you want to keep reusable (e.g. qsort()). In C++, see the STL (Standard Template Library).
2) Asynchronous or synchronous event handling - anyway event has to be identified, based on which element no. in function pointer array got updated. But the same can be also done via direct call.
Some event systems are designed so that you simply configure which function(s) will be triggered when a given event happens. If this is an external library with a C interface, they have no choice but to use function pointers.
Some other systems let you create your own event loop and you fetch the events somehow and do whatever you want with them; so they avoid callbacks.
3) In some post I had seen people commenting it is to be used when it is not known which function to call. I didn't get any proper justification for this.
See the first case.
Thanks all for actively participating in this discussion. Thanks for giving practical examples like -
1) Implement Library function
2) Look qsort
3) Refer Linux Kernel
4) Generic Heap data structure in C
I feel qsort() void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*)) s is quite sufficient to clear my 1) & 3) point.
1) callbacks - same can be achieved by direct call.
3) In some post I had seen people commenting it is to be used when it is not known which function to call. I didn't get any proper justification for this.
Mainly by callbacks - it is a provision of calling a function for which the body is not yet defined. And it expected that the definition of the function will be provided later during run-time. So, compilation won't be hindered due to lack of function definition. Practical use if someone consider above qsort() function. In this the user is responsible for providing the function definition for compare() like -
int compare (int* a, int* b)
{
//User defined body based on problem requirement
}
Lets consider a practical scenario where multiple threads have their respective compare function. In case of direct call every thread need to implement their own sorting function or if a common function then implementation would be much more bulky. But by using the callback method all threads can use same function for sorting, since the sorting algo remain same for all threads.
Considering a layered architecture mainly higher layers have an abstract view of lower layer. So, here if say we have qsort() function [User defined qsort] implemented at application layer and lets say underlying application there is a ADC driver layer which capture sample and provide to application for sorting. Then for application it is not necessary to understand the definition of function responsible for collecting and providing the samples. But application will only focus on obtaining the sample. Hence, that main application won't know which function to call. Respective ADC driver will simply make a call to application using the qsort() and provide needful data.
Regarding 2 point still confused -
2) Asynchronous or synchronous event handling - anyway event has to be identified, based on which element no. in function pointer array got updated. But the same can be also done via direct call.
From above discussion I conclude that if event handlers pointed to some library function, then it need to be implemented via pointer to function. And secondly to create an independent and handy code it is necessary to maintain function pointer. Lets say between application and driver we have an interfacing layer. So, if either application or driver changes anytime it won't affect or very least affect each other. And this interface layer is implemented using pointer to function. But consider below scenario -
int (*fptr[10]) (void) =
{
function1; //function for starting LED
function2; //function for relay operation
.
.
function10; //function for motor control
}
lets say we have GPIO0.0 - GPIO0.10 has been mapped to the function pointer array. i.e. GPIO0.0 - 0th element of fptr
.
.
GPIO0.10 - 10th element of fptr
These GPIO pins has been configured for level triggered interrupt and their respective ISR will update the array element no. i=GPIO_Value; further the scheduler have an thread which will call the function pointer array -
fptr[i]();
Does the use of function pointer is justifiable here??
This is something that recently crossed my mind, quoting from wikipedia: "To initialize a function pointer, you must give it the address of a function in your program."
So, I can't make it point to an arbitrary memory address but what if i overwrite the memory at the address of the function with a piece of data the same size as before and than invoke it via pointer ? If such data corresponds to an actual function and the two functions have matching signatures the latter should be invoked instead of the first.
Is it theoretically possible ?
I apologize if this is impossible due to some very obvious reason that i should be aware of.
If you're writing something like a JIT, which generates native code on the fly, then yes you could do all of those things.
However, in order to generate native code you obviously need to know some implementation details of the system you're on, including how its function pointers work and what special measures need to be taken for executable code. For one example, on some systems after modifying memory containing code you need to flush the instruction cache before you can safely execute the new code. You can't do any of this portably using standard C or C++.
You might find when you come to overwrite the function, that you can only do it for functions that your program generated at runtime. Functions that are part of the running executable are liable to be marked write-protected by the OS.
The issue you may run into is the Data Execution Prevention. It tries to keep you from executing data as code or allowing code to be written to like data. You can turn it off on Windows. Some compilers/oses may also place code into const-like sections of memory that the OS/hardware protect. The standard says nothing about what should or should not work when you write an array of bytes to a memory location and then call a function that includes jmping to that location. It's all dependent on your hardware and your OS.
While the standard does not provide any guarantees as of what would happen if you make a function pointer that does not refer to a function, in real life and in your particular implementation and knowing the platform you may be able to do that with raw data.
I have seen example programs that created a char array with the appropriate binary code and have it execute by doing careful casting of pointers. So in practice, and in a non-portable way you can achieve that behavior.
It is possible, with caveats given in other answers. You definitely do not want to overwrite memory at some existing function's address with custom code, though. Not only is typically executable memory not writeable, but you have no guarantees as to how the compiler might have used that code. For all you know, the code may be shared by many functions that you think you're not modifying.
So, what you need to do is:
Allocate one or more memory pages from the system.
Write your custom machine code into them.
Mark the pages as non-writable and executable.
Run the code, and there's two ways of doing it:
Cast the address of the pages you got in #1 to a function pointer, and call the pointer.
Execute the code in another thread. You're passing the pointer to code directly to a system API or framework function that starts the thread.
Your question is confusingly worded.
You can reassign function pointers and you can assign them to null. Same with member pointers. Unless you declare them const, you can reassign them and yes the new function will be called instead. You can also assign them to null. The signatures must match exactly. Use std::function instead.
You cannot "overwrite the memory at the address of a function". You probably can indeed do it some way, but just do not. You're writing into your program code and are likely to screw it up badly.
The title is not that clear, and if anybody has a better suggestion please tell me.
Now to business:
I am activating a class' method.
m_someObject.Clear();
The problem is that when I look at the address of m_someObject before the call I get that it is located in a certain address, and when I enter the Clear method with the debugger I get that this variable is located in another address.
The result is that after returning from Clear method it doesn't seem to have affected
m_someObject instance which called it.
Does anybody have any idea what could cause this kind of behavior?
Working on Microsoft Visual Studio 2010 64-bit.
Probably you pass m_someObject as a value to some other function (and thus get a copy) and execute Clear() only on copy. This way you will not notice a change on original object.
Can you please check if you have two different variables with the same name? One defined in the immediate scope and another one, maybe in the global scope?
The most common reason is Multiple Inheritance. Unlike C# and Java, in C++ a class can have multiple base classes. Obviously, not all can be located at offset 0. This means that this has to be adjusted if you're using a method from a base class that's located at a non-zero offset.
Well, apparently the debugger was lying.. I wasn't aware of this, but apparently some of the code was compiled in release mode. Conclusion - Debugger No, printf - Yes.
Ran into the ReferenceTable limit in my Android jni function. Cleaned it up with DeleteLocalRef, but I want to know if I should do the same for the arguments passed to the function from Java. Is it possible? If so, is it worthwhile?
Local references are created within a native method only. I dont think it is worthwhile doing that for the function arguments. Best practice will be to delete the local references if you are doing anything in a loop, or creating a lot. Take a look at sun's reference
I'm chasing a bug where a member value of an object seems to magically change, without any methods being called which modify it. No doubt something obvious but proving hard to track down.
I know I can put conditional break-points in methods based on the variable value, but is it in any way possible to actually put a breakpoint on a variable itself? e.g a breakpoint which fires when x==4? I know I can put watches on, what about breakpoints?
Edit: this is a native-only project, no managed malarkey.
You can use a data breakpoint. There are a number of restrictions about how and when they can be used, namely that they work only in native code.
(To the best of my knowledge, you can only tell it to break when the variable changes, not when it changes to a specific value, but I'm not entirely sure; most of my code is mixed managed/native and thus can't use data breakpoints).
What you should do is just wrap the variable in a set/get - not just a template functions but actually in a separate class, where set/get MUST be used to access. Then put a breakpoint in there. Alternatively, for easier chop and change, you could wrap the value in a class, and use operator overloads (with appropriate breaks in) to alter. That's probably the cleanest and most portable solution.
What you may also find is that the variable being modified is not in ways you expect. Best example I've got is that I had unsigned int where I subtracted from zero when I meant to increment from zero, so when I was looking for places that I knew modified it, that didn't flag up. Couldn't work out wtf was going on.
However, as far as I know, VC++ supports no mechanism to break on arbitrary changes, if the data breakpoint won't work for you. for example, if it was changed due to stack/heap corruption. But if you're running in debug, I'd expect that VC++ would break on those.