destroying buttons from a vcontainer - c

I have a vcontainer which is populated with a gtk_combo_box and several buttons
i would like to clear the buttons only from within the vcontainer, I tried the following code:
GList *vcontainer_children, *iter;
vcontainer_children = gtk_container_get_children(GTK_CONTAINER(container));
for(iter = vcontainer_children; iter != NULL; iter = g_list_next(iter))
{
if (gtk_button_get_label(iter));
gtk_widget_destroy(GTK_WIDGET(iter->data));
}
the code clears all widgets in the vcontainer, one possibility would be to replace the if with a function that checks whether iter is a button or not, but I do not know how that is done

if (gtk_button_get_label(iter));
The semicolon at the end is wrong; this is the same as saying
if (gtk_button_get_label(iter))
/* do nothing */;
and as such the gtk_widget_destroy() always runs.
Simply remove the semicolon or switch to using braces for everything (or some other option I didn't think of).
Your condition is also wrong for two reasons. First, it uses iter instead of iter->data. Second, it will crash and burn spectacularly if the widget isn't a button. Fortunately there's a macro GTK_IS_BUTTON() you can use instead:
if (GTK_IS_BUTTON(iter->data))
gtk_widget_destroy(GTK_WIDGET(iter->data));

Related

using Dynamic array of HANDLE(void*) with createThread(...)

I'm a beginner in C and in threading in particular.
I need to malloc and use dynamic array of HANDLE that later would be used in WaitForMultipleObjects.
What I do now:
int i = 0 ;
HANDLE ThreadHandlers = (HANDLE)malloc(sizeof(HANDLE)* List->logicalLength);
Then in a loop:
while(curr!= NULL)
{
ThreadHandlers[i]= createtestThread((LPTHREAD_START_ROUTINE)executeTest,(TestStruct*)(curr->data),ThreadIds+i);
curr = curr->next;
//ThreadHandlers[i] =
i++;
}
WaitForMultipleObjects(
List->logicalLength,
ThreadHandlers,
TRUE, /* wait until all threads finish */
INFINITE);
But when I try to compile, it I get:
IntelliSense: expression must be a pointer to a complete object type
Which from my understanding is because HANDLE is typedef void*
and I cant do logic with void*.
What workaround can be done?
What is the right way to do that kind of programming? (waiting for unknown amount of threads)
This line:
HANDLE ThreadHandlers = (HANDLE)malloc(sizeof(HANDLE)* List->logicalLength);
Should be this:
HANDLE* ThreadHandlers = (HANDLE*)malloc(sizeof(HANDLE) * List->logicalLength);
That above fix will resolve your compile problem with regards to WaitForMultipleObjects.
And while I'm here, this line looks suspicous:
ThreadHandlers[i]= createtestThread((LPTHREAD_START_ROUTINE)executeTest,(TestStruct*)(curr->data),ThreadIds+i);
I assume createtestthread is a wrapper for CreateThread or _beginthreadex. But if you have to explicitly cast your function explicitly to LPTHREAD_START_ROUTINE, you have probably done something wrong. Remove the cast such that this line becomes:
ThreadHandlers[i]= createtestThread(executeTest,(TestStruct*)(curr->data),ThreadIds+i);
Then if that still leads to a new compiler error, fix the declaration of executeTest such that it's declared as follows:
DWORD __stdcall executeTest(void* pData);
Forcing a function of a different signature into CreateThread will lead to weird problems later on.
You've made a mistake in creation of array of handles, what you should do is:
HANDLE *ThreadHandlers = (HANDLE*)malloc(sizeof(HANDLE) * List->logicalLength);
As far as your second question goes, using WaitForMultipleObjects is the right way to wait for an unknown amount of threads. Depending on the situation, you could pass FALSE as third parameter if you want to wait only until one thread gets signaled, or pass some time-out interval as fourth argument if you want to stop waiting after a certain period.

gtk_container_get_children

When list of stations is printed in Preset rol list and you are at the begining or at the end of the list, you see many empty items.
I create list of about 20 stations and try to display them, go to the begining and to the end of the list.
I think the problem is in this piece of code:
static void add_button_clicked_cb(GtkWidget *widget, gpointer data)
{
preset *ps;
gchar *buffer;
GtkTreeIter iter = {0};
GtkAdjustment* v_scb;
GtkTreePath *path = NULL;
GList* menuitems;
GtkWidget *menuitem;
ps = malloc(sizeof(preset));
ps->title = g_strdup(_("unnamed"));
ps->freq = rint(gtk_adjustment_get_value(adj)) / STEPS;
settings.presets = g_list_append(settings.presets, (gpointer) ps);
buffer = g_strdup_printf("%.2f", ps->freq);
gtk_list_store_append(list_store, &iter);
gtk_list_store_set(list_store, &iter, 0, ps->title, 1, buffer, -1);
g_free(buffer);
gtk_tree_selection_unselect_all(selection);
v_scb = gtk_scrollable_get_vadjustment(GTK_SCROLLABLE(list_view));
gtk_adjustment_set_value(v_scb, gtk_adjustment_get_upper(v_scb));
if (main_visible) {
gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(preset_combo), ps->title);
mom_ps = g_list_length(settings.presets) - 1;
preset_combo_set_item(mom_ps);
menuitems = gtk_container_get_children(GTK_CONTAINER(tray_menu));
menuitem = gtk_menu_item_new_with_label(ps->title);
gtk_menu_shell_insert(GTK_MENU_SHELL(tray_menu), menuitem, mom_ps);
g_signal_connect(G_OBJECT(menuitem), "activate", (GCallback)preset_menuitem_activate_cb, (gpointer)mom_ps);
gtk_widget_show(menuitem);
}
buffer = g_strdup_printf("%d", g_list_length(settings.presets) - 1);
path = gtk_tree_path_new_from_string(buffer);
g_free(buffer);
gtk_tree_view_set_cursor(GTK_TREE_VIEW(list_view), path, NULL, FALSE);
gtk_tree_path_free(path);
}
Could you please suggest me how can correct it?
Inside of the if (main_visible), you have:
menuitems = gtk_container_get_children(GTK_CONTAINER(tray_menu));
That is, you're setting the value of menuitems to the return value of that function call. However, none of the rest of your code actually does anything with menuitems. So, the compiler gives you that warning.
Fixing it might be as easy as simply getting rid of menuitems:
gtk_container_get_children(GTK_CONTAINER(tray_menu));
That would definitely get rid of the warning. But you have to think about it: Maybe you should be doing something with the return value of that function call, and the reason that you're not doing anything with it is that you forgot to (or whatever).
warning: variable 'menuitems' set but not used
Your compiler in layman's terms is saying the following:
Dude... youve created a class with a few attributes, one of which are called 'menuitems'. That's all well mate, but when you actually create an instance and assign all the variables, youve set 'menuitems' but youre never using that variable to do anything with it. its just sitting there doing nothing at all. So mate it's no problem at all as I can still run your program but im just warning you that the 'menuitems' variable is doing ** all as you're never using the variable itself. Just warning you bro :D other than that have a good day
So its just a warning to let you know you have a variable no being used for any specific reason other than storing a value in there but never accessing it to do something useful. So either comment it out since youre not actually doing anything with it.. or use it, or just enjoy reading the warning but it wont affect the way your program runs.
The warnings get displayed mainly to get the developer more aware of their own code and whats happening.

Exit C function cleanly

I have a couple of functions. Basically a menu where a user can choose 1-n different options, and each of those options have a function associated with them. In this example it's been dumbed down.
What I am trying to determine is the best way to exit a function prematurely. For example, when the user presses enter whilst in the function of a menu option, I want the program to send them back to the menu without running anything else in that function.
In the case below, I simply call showMenu() and place a return statement after it. The only thing is, if the user quits multiple functions there will be a trail of return statements that needs to be unraveled at the end.
Could somebody please show me if there is a more efficient way to achieve this or whether I am on the money.
void showMenu()
{
//Display menu
//Prompt user for menu option
//Run function of appropriate menu option
runSelectedFunction();
}
void runSelectedFunction()
{
//Get user input for the function and validate
//Check if the user input was only a '\n' if so show the menu and exit
showMenu();
return;
//Do the stuff that this function is meant to do.
}
Looks good to me. Or - since there are many around that are against having multiple exit points form a single function - you could do:
void func()
{
//get input
if ( checkMenu() )
{
//do the stuff I am meant to do
}
else
{
showMenu();
}
}
so you are avoiding adding a second return to your function. Also you could have the showMenu() call always at the end of the function, depending on your needs
hth
Mario
The best way? In short, don't.
Why?
Although there's nothing technically wrong with it and you'll find it all over the place, it can sometimes lead to headaches when trying to track down bugs or memory leaks in complex code.
Use early returns only when absolutely necessary and even then try to find an alternative first :)
An alternative is to use the following pattern to ensure your function always returns from one place, giving you the opportunity to always free resources (or report errors, etc):
int func(void)
{
int ret = 0;
do
{
if (!allocate_resource())
{
ret = -1;
break;
}
if (!allocate_more_resources())
{
ret = -2;
break;
}
do_stuff();
}
while (0);
free_allocated_resources();
return (ret);
}

I have a function with a lot of return points. Is there any way that I can make gdb show me which one is returning?

I have a function with an absurd number of return points, and I don't want to caveman each one, and I don't want to next through the function. Is there any way I can do something like finish, except have it stop on the return statement?
You can try reverse debugging to find out where function actually returns. Finish executing current frame, do reverse-step and then you should stop at just returned statement.
(gdb) fin
(gdb) reverse-step
There is already similar question
I think you're stuck setting breakpoints. I'd write a script to generate the list of breakpoint commands to run and paste them into gdb.
Sample script (in Python):
lines = open(filename, 'r').readlines()
break_lines = [line_num for line_num, line in enumerate(lines) if 'return' in line and
line_num > first and line_num <= last]
break_cmds = ['b %s:%d' % (filename, line_num) for line_num in break_lines]
print '\n'.join(break_cmds)
Set filename to the name of the file with the absurd function, first to the first line of the function (this is a quick script, not a C parser) and last to the number of the last line of the function. The output ought to be suitable for pasting into gdb.
Kind of a stretch, but the catch command can stop on many kinds of things (like forking, exiting, receiving a signal). You may be able to use catch catch (which breaks for exceptions) to do what you want in C++ if you wrap the function in try/finally. For that matter, if you break on a line inside the finally you can probably single-step through the return after that (although how much that will tell you about where it came from is highly dependent on optimization: common return cases are often folded by gcc).
How about taking this opportunity to break up what seems to be clearly a too-large function?
This question's come up before on SO. My answer from there:
Obviously you ought to refactor this function, but in C++ you can use this simple expedient to deal with this in five minutes:
class ReturnMarker
{
public:
ReturnMarker() {};
~ReturnMarker()
{
dummy += 1; //<-- put your breakpoint here
}
static int dummy;
}
int ReturnMarker::dummy = 0;
and then instance a single ReturnMarker at the top of your function. When it returns, that instance will go out of scope, and you'll hit the destructor.
void LongFunction()
{
ReturnMarker foo;
// ...
}

Breakpoint when variable takes on a certain value

I have something analogous to the following code...
void function(int x)
{
// complicated operation on x
blah
blah
}
It all appears to be working fine except when x happens to be a particular value, say "273". But x being 273 is a rare event, 99.999% of the time it is some other value. Now I wish to observe the events when this function is called with x=273, so I would like to insert a breakpoint that gets hit only with x is that value. Perhaps I could do it like this:
void function(int x)
{
if (x == 273)
{
// put breakpoint on this line.
}
// complicated operation on x
blah
blah
}
The problem is that presumably the compiler will optimise away this "if" statement because it doesn't do anything. So my question is what should I put within the "if" statement to to make sure it gets compiled in to something... or should I be tracing the x==273 case in some completely different way.
It sounds like what you're looking for is conditional breakpoints. These are a feature of Visual Studio which allow a break point to only be hit when a very specific condition is true.
To do this, put a break point at the start of the function. Then right click on it and select "Condition". Then add following expression
x == 273
Now you can debug this without changing your source binary.
Maybe just use a conditional breakpoint? Have a look here how to set it up.
Create new conditional breakpoint (right click breakpoint and select "Condition...") and put
x == 273
as a condition.
if (x == 273)
{
volatile int tmp = 0; // This is not get optimized
}
In cases when I need a real line to set a breakpoint to i use something similar:
{
int i = 42;
}
It get optimized away but I may get a compiler warning for unused variable. But a conditional breakpoint (other answers) is probably better in this case

Resources