Thursday, May 24, 2007

some c code to debug

...dumping an old post from my older WordPress blog:

I stumbled upon http://www.advagato.org today and spent a few minutes trying to solve this “spot the bug” quiz.

According to the person who posted it, the challenge is to find atleast 2 memory-related bugs in the code (potential memory leak and/or a dangling pointer creation) in the mydata_add() function:

typedef struct {
int count; // number of items in each array
Foo* foos; // array of Foos
Bar* bars; // array of Bars
} MyData;

Now, here’s the function used to add a (foo,bar) pair to the data structure:

static int
mydata_add( MyData *data, Foo foo, Bar bar )
{
Foo* new_foos;
Bar* new_bars;
int count = data->count;
 if ( count == 0 )
  new_foos = malloc( sizeof(Foo) );
else
new_foos = realloc( data->foos, sizeof(Foo)*(count+1) );
if ( new_foos == NULL )
return -1;
if ( count == 0 )
new_bars = malloc( sizeof(Bar) );
else
new_bars = realloc( data->bars, sizeof(Bar)*(count+1) );
if ( new_bars == NULL )
return -1;
new_foos[count] = foo;
new_bars[count] = bar;
data->foos = new_foos;
data->bars = new_bars;
data->count = count+1;
return 0;
}

Answer:
First, I had to figure out what realloc() did. According to the man page:

void *realloc(void *ptr, size_t size);

realloc() changes the size of the memory block pointed to by ptr to
size bytes. The contents will be unchanged to the minimum of the old
and new sizes; newly allocated memory will be uninitialized. If ptr is
NULL, the call is equivalent to malloc(size); if size is equal to zero,
the call is equivalent to free(ptr). Unless ptr is NULL, it must have
been returned by an earlier call to malloc(), calloc() or realloc().
As for the answer to the original question:

The two memory errors was basically of the same type. It happens when the second allocation fails (either malloc() or realloc()):
1. In the case when count was 0, it would leak a newly allocated (malloc()) block of memory.
2. In the case when count was > 0, it would have reallocated the block pointed by data->foos, but would not have updated the corresponding pointer. Now in this memory block would not be in the same position as the original one (before the realloc()), which would be more or less the case, we would have created a dangling pointer.

Wednesday, May 23, 2007

Whats the time?

I had a very interesting and amusing realization today. After a few months of not having that extra "cash" that I use for doing my investing, I finally have enough to make a decent purchase and take one more step towards that ideal-balanced portfolio .

Now, I have been keeping an eye out on a few ETFs that my portfolio could certainly use right now. I am way too lean on small cap (growth or value) and financials. That is true even for Energy, but that is a whole new topic. I have sort of convinced myself that the next purchase is going to be either a small cap or a financial ETF.

As I look at the market today, call me skeptical, but I don't feel too comfortable buying right now. It all comes back to basics of investing.
1. Don't try to time the market.
2. Dollar-Cost-Avg out everything you buy and everything you sell.

Well, I have never been able to get to #2 with my "taxed" investing portfolio. I leave that for the 401k (...also another topic of interesting discussion as to why most...well..if not most, at least most small investors I know never treat their 401k and their active-investing accounts/portfolios in the same way and with the same principles?). As for #1, I have every reason to believe Karma has something to do with it. Either that, or for some reason, the economics of the world somehow scheme together so that every time that I have my investing money ready, it is NEVER a good time.

So, for somebody like me, who has not yet figured out how to get $$-cost-avg to blend into my lifestyle (to be fair....I haven't heard it mentioned any time before, but THAT is a pretty hard thing to achieve), for now timing is pretty much everything. I am probably just going to wait for a short dip...hopefully which should happen sometime soon or else I am sure that money is magically going to disappear soon into the unrelenting appetite for my money that day-to-day living has!

On a positive not, I still need to verify this, but remember reading somewhere that Zecco pays decent (around 4%) interest for money that you transfer, but not invest into your account. I should probably do that transfer instead of writing this right now...........

Sunday, May 20, 2007

useful reading


Some time ago I had convinced myself that if identified a few good financial bloggers, the power of that combined with my 5-year subscription to Money and Kiplinger's magazines, would provide me with enough arsenal to be a better investor.
About 6 months down the line, I am not sure how effective those have been, but I would like to believe that it certainly hasn't done any harm. I haven't gone off to buy the top 10 funds that come out monthly in either of the magazines, nor have I found tips on hot markets or stocks/funds from any of the blogs that has made me rich over night.

In any case, here are a few good links that I read more than a couple of times a week:
http://mymoneyblog.com - very popular
http://bankdeals.blogspot.com - haven't really been able to use any of the information that i have come across on here, but do give it a look before I do anything else with my money.
http://www.thebuylist.com - I need to figure out if there is an effective way to use this information.

Also, had stumbled upon this article from Morningstar which has links to a couple of useful tools for personal portfolio checkups.

I have also been listening to a couple of podcasts which though not particularly focused on stocks in general, do offer some sensible tips ever so often:
http://money-guy.com
http://moneygirl.qdnow.com

I guess till I figure out if these are not really helping or significantly hurting my investing decisions, I would gladly keep these around as long as my daily routine permits it.

some pthread basics

So it doesn't look like I will be able to sustain two separate blogs, one for stocks and the other for software. I am almost convinced that I should change the name to "Bits and Bulls" which should sum up the two things I am most likely to write about; software and stocks.

Well, to get me started, I was reading up on some thread basics and saw this simple and basic pthread_create implementation. Could be a good c programming interview question:

Question: What is wrong with this simple code?

/* Parameters to print_function. */
struct char_print_parms
{
/* The character to print.*/
char character;
/* The number of times to print it. */
int count;
};

/* Prints a number of characters to stderr, as given by PARAMETERS,
which is a pointer to a struct char_print_parms. */
void* char_print (void* parameters)
{
/* Cast the cookie pointer to the right type. */
struct char_print_parms* p = (struct char_print_parms*) parameters;
int i;

for (i = 0; i <>count; ++i)
fputc (p->character,stderr);
return NULL;
}

/* The main program. */
int main ()
{
pthread_t thread1_id;
pthread_t thread2_id;
struct char_print_parms thread1_args;
struct char_print_parms thread2_args;

/* Create a new thread to print 30,000 ‘x’s. */
thread1_args.character = ‘x’;
thread1_args.count = 30000;
pthread_create (&thread1_id, NULL, &char_print, &thread1_args);

/* Create a new thread to print 20,000 o’s. */
thread2_args.character = ‘o’;
thread2_args.count = 20000;
pthread_create (&thread2_id, NULL, &char_print, &thread2_args);

return 0;
}


Answer: The main thread (which runs the main function) creates the thread parameter
structures (thread1_args and thread2_args) as local variables, and then passes pointers to these structures to the threads it creates.

So, it is very much possible that Linux will schedule the three threads in such a way that main finishes executing before either of the other two threads are done? So, if this happens, the memory containing the thread parameter structures will be deallocated while the other two threads are still accessing it.

Solution:
/* Make sure the first thread has finished. */
pthread_join (thread1_id, NULL);
/* Make sure the second thread has finished. */
pthread_join (thread2_id, NULL);

Wednesday, May 16, 2007

Microlending for mainstream - kiva.org


I had read about kiva.org from a financial blogger who I read fairly often. Yesterday while watching local PBS in HD (since it is either that or Discovery that seem to have the only decent quality HD programming) that I saw a good segment on kiva and spent some time today looking into it.

I guess enough has been said about the creativity of the idea and the ease and effectiveness of it on various blogging sites. The 100% repayment rate so far is certainly impressive and it seems to be getting more attention each day.

I am not a charitable person when it comes to donating money, but this appeals to even my charitable side. Of course micro-lending is not charity. However, I am looking at it as most people like me would do; Loan some amount that you are comfortable with, hope that it helps someone with the need to get setup or make a small business work. If that works, I suppose the feeling of having helped can only be good. When the repayment comes across, I am sure you are not going to need the money then, so see if you can help someone else. Call it pseudo-charity, but this is something I could see myself doing with the selfish reason of enjoying the feeling of having helped.

I like ideas like this that work.