views:

458

answers:

4

Hi, I'm using a struct like this:

define struct _Fragment{
     int a;
     char *seq;
}Fragment;

I want to initialize the struct, and using the malloc() method return a dynamic memory like this

Fragment *frag=malloc(10*sizeof(Fragment));

Then I would using the frag pointer like this:

frag->seq="01001";

Then the problem occurs when I returns a lot of Fragments. the error message said that (using valgrind tool):

Uninitialised value was created by a heap allocation

who can tell me how I can deal with it. thank you!

+3  A: 

I'm not sure you have a real problem here, but for proper etiquette, your allocation would be:

Fragment *frag=malloc(10*sizeof(Fragment));
if (frag) memset(frag,0,10*sizeof(Fragment));
Dave Gamble
it's easier to just use calloc()
Juliano
+4  A: 

The problem is that even though you use malloc to allocate memory for a Fragment structure, you haven't initialized any of the values. The memory returned by malloc is not guaranteed to be any specific value so you must explicitly initialize the struct members

Fragment* frag = malloc(10*sizeof(Fragment));
int i = 0;
for ( i = 0; i < 10; i++ ) { 
  frag[i].a = 0;
  frag[i].seq = NULL;
}

If you want guaranteed initialized memory you should use calloc. It has an added cost of zero'ing out the memory but it may not be significant for your app.

Also you should check that malloc actually succeeds :)

JaredPar
A: 

Your code looks plausible, but in the following line;

Fragment *frag=malloc(10*sizeof(Fragment));

Are you sure you need 10* ?

If you need to allocate 10 Fragments, then you should take responsibility for initializing all 10.

Bill Forster
No, the number of I want to get is dynamic.
Charlie Epps
Okay then, if you need 10, you need to initialize 10! In your code you initialized only one field of the first Fragment.
Bill Forster
+1  A: 

The issue is malloc does not initialize any of the memory it allocates. Valgrind takes particular care to keep track of any regions of memory that have not been initialized.

You should probably take heed of the error though, the only reason Valgrind (Assuming everything works correctly) should print that error is becuase you attempted to make use of the uninitialized data somewhere, which is probably unintended. The use of unitialized variables is not in the code you have in your question, however.

Falaina