Re: appending a clist row



learfox furry ao net wrote:

if(text != NULL)
{
        /* Set each pointer to point to an allocated empty string. */
        for(i = 0; i < clist_columns; i++)
                text[i] = strdup("");
}

just for my curiosity: why do you use strdup() instead of passing the
const char * "" ?

I got the impression that the array and or strings within would be
modified.

hmm, a const char* like "bla" or "" is allocated at compiletime and
overwriteing such a string will easyly result in a segfault or buffer
overrun, cause it holds exact as many bytes as necessery.

i meant that someone would easily find errors in his code if he tries to
overwrite const chars, not that they would cause segfaults more often! i
was not telling this clearly, IC!

also you have to free the string to avoid a memory leak if you code
is executed more than once.

when dynamically allocated strings are used of course.
 
Right, that's what I was saying. :)

i didn't understud it this way, sorry!

I don't know if they are so just to be on the safe side I made coppies.

gtk will hold its own copies, so the dynamically allocate memory is
wasted and can not be freed at runtime. instead of doing:

Dynamically allocated memory can never be free()'ed? O.o

dynamically allocated memory MUST ALLWAYS be freed. but you cannot do it
when you hold your strings in it.
 
text = (char **)malloc(clist_columns * sizeof(char *));

you should do:

char *text[COLUMNS];

for(i = 0; i < COLUMNS; i++) text[i] = "";
gtk_clist_append(GTK_CLIST(list), &text[0]);

i hpe i'm not telling bullshit here!!!! ;-)
warm regards ...
clemens

Well no, what you were saying is basically assuming that the buffers are
not modified by gtk_clist_append().

The original post hinted, that the user wanted modifyable array of
strings, hence is why I suggested to allocate each one, passing, then
deallocating.

this way its ok, but like i said. its no problem to just set the text
with constant chars instead of allocating mem, writing content to that
mem, passing a pointer to that mem to gtk_set_text() and deallocating
the mem. its also save to pass pointers to strings anywhere in memory to
gtk_clist_append() without strdup() it. if gtk would rely on the
strdup()'ed string you could not free() it anyway. however - at least it
depends on taste and programming style, what way someone prefers. doing
much code the last few months made me avoiding strdup() and malloc()
wherever possible. just my two cents!

best regards ...
clemens




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]