elfs: (Default)
[personal profile] elfs
What follows is geek talk.

So, I'm trying to write this chunk of code. I don't know anything about writing UI's for dynamic systems, such as X; most of my work has been in the web world. My C is unimaginably rusty; I find myself intimidated thinking about pointers. So, as I'm hacking my way through it, I think to myself, "I need a lookup function for a list." No problem, there's an example for how to do this in the Developing Applications For Linux book. I have the source code examples on my hard drive, and I go seek one out to see how it works.

Here's the example from the book:
 list = g_slist_insert_sorted (list, "Wilma", CompareNames);
g_strlcpy (buffer, "Wilma", 87);
node = g_slist_find(list, buffer);


This code fails!. I tried hacking it.
list = g_slist_insert_sorted (list, "Wilma", CompareNames);
node = g_slist_find(list, "Wilma");


This code succeeds. At first glance, they're the exact same code, but with a subsitution of the full string for a variable that contains the string. Finally, I go look at the documentation for lists and try something else:
list = g_slist_insert_sorted (list, "Wilma", CompareNames);
g_strlcpy (buffer, "Wilma", 87);
node = g_slist_find_custom (list, buffer, CompareNames);


Okay, here's what's going on. The "find" function does a straight comparison. Does the data in the list entry match the data being passed in. It's a simple "x = y". But strings are not straight comparisons; the buffer and the list-data are two copies of the word "Wilma" stored at different addresses. It was the addresses that were being compared, and since they're different, the function failed. In the third example, I needed to write a custom function that would take the two addresses and compare the contents stored at those addresses.

Why did it work in the second example? Ah, here's where knowledge of how compilers works comes in. The compiler saw the word "Wilma" and saw a collection of data exactly like another static collection of data earlier in the program, so it tried to be clever and set both statically established buffers to the same address.

I suppose this makes for an interesting learning example, but I'd like to know why it was shipped to me wrong in the first place!

Date: 2003-10-18 10:17 pm (UTC)
From: [identity profile] ashley-y.livejournal.com
This is why I write code in a language which makes it almost impossible to make this kind of mistake (and no, I don't mean Java).

Profile

elfs: (Default)
Elf Sternberg

December 2025

S M T W T F S
 12345 6
78910111213
14151617181920
21222324252627
28293031   

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Dec. 27th, 2025 07:03 pm
Powered by Dreamwidth Studios