Click to See Complete Forum and Search --> : a question about malloc


question
April 24th, 1999, 08:20 AM
I write a program with c for digital unix.I use malloc to ask for some space to use and free it later.But the malloc will fault when the program run for a long time.Who can tell me what about the malloc function.Thanks.

eric33
April 24th, 1999, 10:40 AM
This seems to be a problem of non freed resources.
Dont forget to free malloc resources with free functions because of fragmented memory problems.

April 24th, 1999, 01:55 PM
malloc can be a bit tricky, as the previous reply stated, you MUST free up the space you requested, but you also have to ask for the right amount of space, for example if I want a char * that will hold a 30 character string, the following will fail:
char *my_string;
my_string = (char *) malloc(sizeof(char) * 30);

It will either cause a segmenation violation, a sigbus, or it will work fine. The problem is that you of course need 31 bytes for a string that is 30 long, 30 for the string and one for the null terminator. I've had this problem cause some very hard to track down errors. Hope this helps.

question
April 24th, 1999, 07:28 PM
I has free what I had asked for.I use a struct like this:
struct str{
char name[11];
int age;
};

struct str temp;

temp=(struct str*)malloc(sizeof(struct str));

when it run some time,it return null.I think it isn't the situation what you said.Do you?