Archive for the ‘C’ Category

How to check the size allocated by malloc

18/11/2009 (quarta-feira)

#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char ** argv)
{
    for(int i = 1; i < 1000; i++)
    {
        size_t *p = (size_t *) malloc(i * sizeof(size_t));
        printf("%zu = %d * %zu\n", *(p - 1), i * sizeof(size_t));
    }
    return 0;
}
Anúncios

Executing code from time to time

5/8/2009 (quarta-feira)

This is a simple way to make a code be executed from time to time, using alarm().

#include 
#include 
#include 

static void
run(int signal)
{
    printf("signal = %i\n", signal);
    alarm(1);
}

int main(int argc, char **argv)
{
    struct sigaction act;

    act.sa_handler = run;
    if(sigaction(SIGALRM, &act, NULL))
    {
        fprintf(stderr, "Error adding handler for SIGALRM.\n");
        return 1;
    }
    alarm(1);
    while(1);
    return 0;
}

gconf_client_add_dir() and remove

5/8/2009 (quarta-feira)

They don’t really create the directory. They just turn on and off listening to them.

g_idle_add()

5/8/2009 (quarta-feira)

When a signal is emitted a lot of times, and the processing of the action associated with the signal is expensive, it’s an option to only run the action when the system is idle. Using this function in this manner, this result can be achieved. I got to know this talking to pierlux in #champlain@irc.freenode.net and taking a look at champlain-marker.c from libchamplain. Thanks.

static gboolean scheduled;

static gboolean
run(gpointer user_data)
{
    /* expensive code */
    scheduled = FALSE;
    return FALSE;
}

static void
on_event(GObject * object, gpointer user_data)
{
    if(!scheduled)
    {
        scheduled = TRUE;
        g_idle_add(run, (gpointer) parameter_name);
    }
}

int main(int argc, char **argv)
{
    /* initialization */
    g_signal_connect(object, "event", G_CALLBACK(on_event), NULL);
    /* enter main loop */
}