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!
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));
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 :)
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.
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.
Related
What am I doing wrong here?
I have a QueueElement struct containing a char* text and a pointer to the next element, so obviously a linked list:
//QElement as in QueueElement
struct QElement {
char* text;
struct QElement* next;
};
typedef struct QElement QElement;
....
void enqueue (char* string){
QElement *new = (QElement *)malloc(sizeof(QElement));
//QElement cast is probably redundant but it doesn't hurt anyone
strcpy (new->text, string);
//some other stuff happening here, linking to other element in linked list,
//but thats not of interest at the moment
}
....
If I try to enqueue a word in the main function, I keep getting segmentation faults and valgrind is telling me, that I'm doing something wrong when I'm using strcpy, so my malloc seems to be incorrect. How do I have to do it?
strdup(.) recommended by other answers is non-standard. If you're not on a Unix platform it may not be available.
However the point is correct. You need to allocate memory to store your string.
Try:
const size_t sz=(strlen(string)+1)*sizeof(*string);//Space required. Including '\0' terminator.
new->text=malloc(sz);//space allocated.
if(new->text==NULL){//sz never 0 because +1.
exit(EXIT_FAILURE);//Allocation failed in non-error handled function.
}
memcpy(new->text,string,sz); //typically fastest way to copy!
Instead of strdup(.).
My use of sizeof(*string) is actually unnecessary (as it is always 1) but the compiler will spot that and it's just good practice.
One day the world will move more uniformly to multi-byte characters and this code is ready for that glorious dawn!
Don't forget to free(.) when you've finished with the 'QElement'.
You should probably write a function like this:
void QElementDestroy(QElement*const element){
if(element==NULL){
return;//Nothing to do!
}
free(element->text);//Needs NULL protection.
free(element);//Does not need NULL protection. But we've done the test anyway!
//NB: Order matters here. A lot.
}
And call it when you've finished with value returned by enqueue(.).
If you want the string to 'out live' the element set element->text=NULL before calling destroy.
free(NULL) is required to do nothing and return normally.
PS: I think strdup(.) is a bit of a n00b trap. They take a while to get the hang of matching malloc(.) and free(.) and strdup(.) is a bit of a traitor because none of the other str... functions allocate space the caller is expected to free(.). It's also non-standard.
in this code
strcpy (new->text, string);
new->text is not allocated memory. It might contain some garbage value, or some write protected memory address or even NULL. Passing that pointer to strcpy() will lead you to Undefined behaviour and as a side effect you may experience the segmentation fault.
You can make use of strdup() or can allocate memory to new->text before strcpy()-ing to that pointer. Both the cases, you need to free() the allocated memory afterwards.
Also,
Please do not cast the return value of malloc().
Check for the success of dynamic memory allocation [malloc()/ calloc()] before using the pointer.
Because you are allocating the memory for structure variable only. You have to allocate the memory in the structure member.
new->text=malloc(10);//for example
After the allocation of memory you can use the strcpy function.
You have allocated the memory for new, but not for the text member variable.
Allocate the memory for text and execute the code.
Program was programmed in C and compiled with GCC.
I was trying to help a friend who was trying to use trying to (shallow) copy a value that was passed into a function. His the value was a struct that held primitives and pointers (no arrays or buffers). Unsure of how malloc works, he used it similar to how the following was done:
void some_function(int rand_params, SOME_STRUCT_TYPEDEF *ptr){
SOME_STRUCT_TYPEDEF *cpy;
cpy = malloc(sizeof(SOME_STRUCT_TYPEDEF));// this line makes a difference?!?!?
cpy = ptr;// overwrites cpy anyway, right?
//prints a value in the struct documented to be a char*,
//sorry couldn't find the documentation right now
}
I told him that the malloc shouldn't affect the program, so told him to comment it out. To my surprise, the malloc caused a different output (with some intended strings) from the implementation with the malloc commented out (prints our garbage values). The pointer that's passed into the this function is from some other library function which I don't have documentation for at the moment. The best I can assume it that the pointer was for a value that was actually a buffer (that was on the stack). But I still don't see how the malloc can cause such a difference. Could someone explain how that malloc may cause a difference?
I would say that the evident lack of understanding of pointers is responsible for ptr actually pointing to memory that has not been correctly allocated (if at all), and you are experiencing undefined behaviour. The issue is elsewhere in the program, prior to the call to some_function.
As an aside, the correct way to allocate and copy the data is this:
SOME_STRUCT_TYPEDEF *cpy = malloc(sizeof(SOME_STRUCT_TYPEDEF));
if (cpy) {
*cpy = *ptr;
// Don't forget to clean up later
free(cpy);
}
However, unless the structure is giant, it's a bit silly to do it on the heap when you can do it on the stack like this:
SOME_STRUCT_TYPEDEF cpy = *ptr;
I can't see why there difference in the print.
can you show the print code?
anyway the malloc causes memory leak. you're not supposed to allocate memory for 'cpy' because pointer assignment is not shallow-copy, you simply make 'cpy' point to same memory 'ptr' point by storing the address of the start of that memory in 'cpy' (cpy is mostly a 32/64 bit value that store address, in case of malloc, it will store the address of the memory section you allocated)
suppose i have a structure :
typedef struct
{
int a;
struct x;
struct *x2;
char *s;
}global_struct;
I have a pointer which points to the memory equal to size of structure :
ptr = calloc(sizeof(global_struct),1);
I actually don't want to allocate memory on the heap and so id declare a variable of the structure as :
global_struct var_struct1;
and i am using memset to initialize the memory to zero.
memset(&var_struct1,0,sizeof(var_struct1))
My code gives segmentation fault when i do this.
I want to know if there's any reason as to why would this fail and under what scenarios?
Is there a difference in the way memory is zeroed by calloc and memset?
No. In fact, calloc likely calls memset internally.
I want to know if there's any reason as to why would this fail and under what scenarios?
No. You have the order of the calloc parameters wrong, it should be calloc(1, sizeof(global_struct));. Although in this case, the ordering of the parameters actually does not matter.
My code gives segmentation fault when i do this.
The problem is likely elsewhere in the code.
There can be a difference. On a vms system, one of the idle time things that can happen is pages in the free list can be zeroed, and moved to a zeroed free list, so that some of the cost behind that calloc may be hidden. Your milage may vary.
I am using the code below to free up malloced memory in the meshes struct, which contains triangleArrays and faces.
This crashes because not every position in the struct has data. What I want to do is only call free if the struct contains data at that member of the array. However using if (self.meshes[meshIdx].triangleArrays[triangleArrayIdx].faces !=NULL) does not seem to work.
for (int meshIdx = 0; meshIdx <=meshTriangleArrays; meshIdx ++) {
for (int triangleArrayIdx = 0; triangleArrayIdx <=1; triangleArrayIdx ++) {
if (self.meshes[meshIdx].triangleArrays[triangleArrayIdx].faces !=NULL) {
free(self.meshes[meshIdx].triangleArrays[triangleArrayIdx].faces);
}
}
}
Calling free on a null pointer is actually fine.
You haven't given enough code to fully diagnose this problem, but a few things to look at:
You need to make sure that self.meshes[...].triangleArrays[...].faces is always initialized, either by a call to malloc (or whatnot), or by setting it to NULL. Otherwise it can (and likely will) be a random garbage pointer that you don't have permission to free.
You need to make sure that all the different self.meshes[...].triangleArrays[...].faces pointers are distinct pointers. You are only allowed to call free exactly once on a malloc'd pointer. For example, something like this:
int * p = (int *) malloc(sizeof(int));
free(p);
free(p); // undefined behavior
can cause a crash.
The below code crashes because not every position in the struct has data.
No, it doesn't crash due to passing a NULL pointer to free(). If you pass in a NULL pointer nothing happens, see the documentation.
What error is being thrown? Show us your initialization code as well, i.e., how are you allocating faces and everything above it? You are likely passing in some bad/uninitialized data to free().
BTW, due to the way you have asked this question I am lead to believe that you think simply declaring an array will fill every element with NULL. This is not the case, they may be filled with anything, and if you pass that to free you will crash (if you're lucky).
How was the triangleArrays array created in the first place? Is it possible that the non-allocated members contain garbage instead of NULL?
EDIT: Updated code with new Pastebin link but it's still stopping at the info->citizens[x]->name while loop. Added realloc to loops and tidied up the code. Any more comments would be greatly appreciated
I'm having a few problems with memory allocation overflowing
http://pastebin.com/vukRGkq9 (v2)
No matter what I try, simply not enough memory is being allocated for info->citizens and gdb is often saying that it cannot access info->citizens[x]->name.
On occasion, I'll even get KERN_INVALID_ADDRESS errors directly after printf statements for strlen (Strlen is not used in the code at the point where gdb halts due to the error, but I'm assuming printf uses strlen in some way). I think it's something to do with how the structure is being allocated memory. So I was wondering if anyone could take a look?
You shouldn't do malloc(sizeof(PEOPLE*)), because it allocates exactly amount of bytes for pointer (4 bytes on 32bit arch).
Seems the thing you want to do is malloc(sizeof(PEOPLE) * N) where N is the max. number of PEOPLE you want to put into that memory chunk.
Clearly the problem lies with:
info->citizens = malloc(sizeof(PEOPLE *));
info->citizens[0] = malloc(sizeof(PEOPLE *));
info->citizens[1] = malloc(sizeof(PEOPLE *));
Think about it logically what you are trying to do here.
Your structs should almost certainly not contains members such as:
time_t *modtimes;
mode_t *modes;
bool *exists;
Instead you should simply use:
time_t modtimes;
mode_t modes;
bool exists;
In that way you do not need to dynamically allocate them, or subsequently release them. The reasons are that a) they're small and b) their size is known in advance. You would use:
char *name;
for a string field because it's not small and you don't know in advance how large it is.
Elsewhere in the code, you have the folllowing:
if(top)
{
PEOPLE *info;
info = malloc(sizeof(PEOPLE *));
}
If top is true then this code allocates a pointer and then immediately leaks it -- the scope of the second info is limited to the if statement so you can neither use it later nor can you release it later. You would need to do something like this:
PEOPLE *process(PEOPLE *info, ...)
{
if (top)
{
info = malloc(sizeof(PEOPLE));
}
info->name = strdup("Henry James");
info->exists = true;
return info;
}
It seems you have one too many levels of indirection. Why are you using **citizens instead of *?
Also, apart from the fact that you are allocating the space for a pointer, not the struct, there are a couple of weird things, such as the local variable info on line 31 means the initial allocation is out of scope once the block closes at line 34.
You need to think more clearly about what data is where.
Lots of memory allocation issues with this code. Those mentioned above plus numerous others, for example:
info->citizens[masterX]->name = malloc(sizeof(char)*strlen(dp->d_name)+1);
info->citizens[masterX]->name = dp->d_name;
You cannot copy strings in C through assignment (using =). You can write this as:
info->citizens[masterX]->name = malloc(strlen(dp->d_name)+1);
strcpy(info->citizens[masterX]->name, dp->d_name);
Or you could condense the whole allocate & copy as follows:
info->citizens[masterX]->name = strdup(dp->d_name);
Similarly at lines 143/147 (except in that case you have also allocated one byte too few in your malloc call).