Re: Example for an dynamically allocated associative array in C
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Sat, 10 Jun 2006 22:42:04 GMT
"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.
.
- References:
- Example for an dynamically allocated associative array in C
- From: Felix H. Dahlke
- Re: Example for an dynamically allocated associative array in C
- From: Chris McDonald
- Re: Example for an dynamically allocated associative array in C
- From: Felix H. Dahlke
- Re: Example for an dynamically allocated associative array in C
- From: Richard Heathfield
- Re: Example for an dynamically allocated associative array in C
- From: Felix H. Dahlke
- Example for an dynamically allocated associative array in C
- Prev by Date: Re: exercise 1-20 K&R
- Next by Date: Re: Why the C committee doesn't provide an implementation when the standard is published?
- Previous by thread: Re: Example for an dynamically allocated associative array in C
- Next by thread: Re: Example for an dynamically allocated associative array in C
- Index(es):
Relevant Pages
|