On Wed, 4 Jul 2007, geoffveale wrote:
> Thanks for all the responses. You have given me a lot to think about.
> The applicable code I am using looks similar to below. The array being
> used is a 2D array and I used a routine I found on the internet to
> create the array using malloc. Any further comments that might show
> problems would be appreciated. The code shown runs most of the time
> without problems. I have never had a crash during creation of the
> array of during initialisation. Problems (seg. faults) seem to happen
> at later stages after the array has been used a few times. Perhaps the
> problem is in another area and the array is an easy target (because of
> the size) for another code messing with the memory??
>
> Geoff Veale
>
>
> #define oops(s) { perror((s)); exit(EXIT_FAILURE); }
> #define MALLOC(s,t) if(((s) = malloc(t)) == NULL) { oops("error:
> malloc() "); }
>
> unsigned char **bin;
>
>
> void main(void){
> various code..
>
> my_subroutine();
>
> return;
> }
>
> void my_subroutine(void){
>
> MALLOC( bin, sizeof( unsigned char *) * 72);
>
> for (i = 0; i < 72; i++) {
> MALLOC( bin[i], sizeof(unsigned char) * 4096);
> }
why don't you just create one big region and treat it as a
multidimensional array? (see below)
> //fill array with zeros
> for ( x = 0; x < 72 ; x++){
> for ( y = 0; y < 4096; y++){
> bin[x][y] = 0;
don't you mean bin[x]->[y] ? after all, this is a pointer to an array of
pointers to arrays, not a (multidimensional) array... with this, you'd be
writing far beyond the end of your array of pointers which is only (72 *
32 bits / 8 bits per byte = 288 bytes) big, hence memory corruption and
segfaults. It just so happens that two consecutive mallocs are likely (but
not certain) to allocate two consecutive areas of memory, which is
possibly why it doesn't segfault immediately.
> }
> }
>
>
> other code..
>
> return;
> }
I expect you'd have better luck with:
void mysub()
{
unsigned char *bin;
unsigned int x, y;
#define XMAX 72
#define YMAX 4096
bin = malloc(sizeof(unsigned char) * XMAX * YMAX);
for (x = 0; x < XMAX; x++)
for (y = 0; y < YMAX; y++)
bin[(x * YMAX) + y] = 0;
}
// same as bin[x][y] if array bounds are known by gcc
// note that (72 * 4096) - 1 == (71 * 4096) + 4095
Yahoo! Groups Links
<*> To visit your group on the web, go to:
http://groups.yahoo.com/group/ts-7000/
<*> Your email settings:
Individual Email | Traditional
<*> To change settings online go to:
http://groups.yahoo.com/group/ts-7000/join
(Yahoo! ID required)
<*> To change settings via email:
<*> To unsubscribe from this group, send an email to:
<*> Your use of Yahoo! Groups is subject to:
http://docs.yahoo.com/info/terms/
|