PDA

View Full Version : [Fixed]about malloc():


sekxx
22nd November 2003, 19:50
Hello guys,
I want to perform somme malloc in a loop,
here is a sample code:
#include <stdio.h>

typedef struct { char * t;} aBuff;

int main(void)
{
aBuff *t;
int len,i;
len = 1000;
t = (aBuff*)malloc(len);
for (i=0; i<len; i++) {
t[i].t = (char*)malloc(255);
}
// freeing memory here...
system("pause");
return 0;
}

This code is to illustrate my trouble with malloc();
if len = 100, it work,
if len >= 1000, it crash.

I have to do up to 1 000 000 malloc in a loop, for my software (a raster to vector image converter).
So if someone know how to perform a "safe malloc" please tell me ;).

PS:
-- I have enough memory to run my code
-- if I put a lot of code in the loop (to speed down iterations)
it work (but this is not a solution)


Thank's,
SeKxX

Nic
22nd November 2003, 21:22
malloc allocates a number of bytes. So you are allocating 1000 bytes to the array.

Really the line should read:
t = (aBuff*)malloc(len*sizeof(aBuff));

And that will allocate the right number of bytes for the array.

Hope that helps,
-Nic

sekxx
22nd November 2003, 22:15
thank's for the reply,

the array t, is an array that contain a structure "aBuff" in each slot [in this code 1000 slot].

the structure, contain a (char *)[here t] (and other stuff[not show in this exemple code]).
so, for each slot, i need to alloc memory for the (char *).
I don't think this can be done without a loop.

I might be wrong in my code [not very confortable with c] so here is the
c++ version of what i want to do:

typedef struct { char * t; int x; int y; sometype somevar;} aBuff;
int main(void){
aBuff *t;
int len,i;
len = 1000;
t = new aBuff[len];
for (i=0; i<len; i++)
t[i].t = new char[255]; //the size of the char is not the same for every t[x].t
// freeing memory here...
return 0;
}

Ps: I have to use ANSI c (so I can't do cpp here)

Nic
22nd November 2003, 22:55
I think your right, you can't do it other than to use a loop. As said simply replacing:
t = (aBuff*)malloc(len);
with
t = (aBuff*)malloc(len*sizeof(aBuff));

Will solve the issue you were having though. Do you any other issue I don't understand?

-Nic

sekxx
23rd November 2003, 00:46
It's working ;)
thank's a lot (sorry, I didn't either tried or understood, the solution you had give to me ;))