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

Re: [MUMmer-help] MUMmer patch for dynamic memory allocation.



On Tue, Sep 15, 2009 at 05:30:53PM -0400, Adam Phillippy wrote:
> Hi Andreas,
> I was not entirely clear. What I meant to say is you cannot do it with a
> single call to malloc and expect the two C bracket operators to behave like
> a 2D matrix would if it had been statically allocated (e.g. D[row][col]).

Well, that's perfectly correct.  If this is done in the patch it is
obviosely the source of the problem.

> For the bracket operators to work, D would have to be an array of row
> pointers each pointing to an int array (or offset in a flat array as you
> suggested). The patch in question does not allocate this separate array of
> pointers. My patch, and the previous mummer-help patches, works similarly to
> your suggestion, but does the indexing with arithmetic rather than pointers
> to save space. It allocates a single array D of size nRows*nColumns and then
> indexes a cell (r,c) by accessing D[r*nColumns+c].

Ahh, OK.  Yes, you can perfectly do the pointer arithmetic on your own.
 
> The latest patch that was forwarded did the following to dynamically
> allocate a 2D matrix of dimension MxN:
> 
> int * D_buf = (int *) calloc ( M*N, sizeof(int) ) ;
> int ** D = &D_buf ;
> 
> This allocates an array of M*N ints pointed to by D_buf. Then it gets a
> pointer to the D_buf pointer and calls it D. Then to access element (r,c) of
> the presumed matrix it would call:
> 
> D[r][c]

Well, that's just wrong, you are right.
 
> The pointer arithmetic would work out to:
> 
> *(*(D+r)+c)
> 
> If D were allocated as a separate array of int (row) pointers and
> initialized as you suggest, this would work. But D is not an array here, it
> is a pointer to the int pointer D_buf. So D+r will be an uninitialized
> location. This is what lead to the memory errors.

OK.  Thanks for the clarification (and sorry if I have stolen your time
to discuss this issue instead of verifying the code in question).

Kind regards

     Andreas.

-- 
http://fam-tille.de
Klarmachen zum Ändern!


Reply to: