Re: Example for an dynamically allocated associative array in C



"Felix H. Dahlke" <fhd@xxxxxxxxxxxxxxxxx> writes:
Richard Heathfield <invalid@xxxxxxxxxxxxxxx> wrote:
The first obvious problem is the first malloc, which should simply be:

tab1 = malloc(sizeof *tab1);

The second obvious problem is the absence of a check of tab1 against NULL
before attempting to dereference it.

Yes, you're right with both.

The third obvious problem is that the second malloc should be:

tab1->column1 = malloc(sizeof *tab1->column1);

(I think it was actually "tabl", not "tab1".)

I think this is right like this. column1 needs to store exactly one
pointer at this point, so the size of 4 bytes (on my machine) should
be perfectly right.

"like this" refers to

tabl->column1 = malloc(sizeof tabl->column1);

which is almost certainly incorrect. tabl->column1 is a pointer to
something. Let's say it's of type FOO*. Even if FOO itself happens
to be a pointer type, you *don't* want to allocate sizeof(FOO*) bytes;
you want to allocate sizeof(FOO) bytes. (Not all pointers are
necessarily the same size.)

Again, the usual idiom to allocate a single object is
ptr = malloc(sizeof *ptr);
or, in this case;
tabl->column1 = malloc(sizeof *tabl->column1);

--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.



Relevant Pages

  • Re: Example for an dynamically allocated associative array in C
    ... The second obvious problem is the absence of a check of tab1 against NULL ... before attempting to dereference it. ... pointer at this point, so the size of 4 bytes should ... My associative array works like this: ...
    (comp.lang.c)
  • Re: Function Call Problem
    ... I am not sure how to correctly write the function call to Tab1. ... also I need to pass this argument as a pointer or reference variable. ... void CTabTestDlg::OnButton1 ... CString s; ...
    (microsoft.public.vc.mfc)