C - Segfault during malloc. Something to do with how I'm using the pointers....
So the place where I'm having a problem is here:
Code:
typedef struct { |
Quote:
You haven't published here full code showing what is happening before you call 'mm_init'. |
This is up to mm_init:
Code:
int main (int argc, char *argv[]){ |
Wait, so do I have to allocate *Mem_Man with memory somehow first?
|
*Mem_Man is allocated. It is a pointer to a structure of type mm_t.
What you have not done is allocate the memory for that structure, and assign the address of that memory to the pointer. Mem_Man = malloc(sizeof(mm_t)) |
So just to make sure I know what you're saying, even though I'm using malloc for the parts of Mem_Man later, to be able to do that I first have to malloc for Mem_Man itself? Thanks a bunch by the way.
|
Pointers have to point to something, or else they point to garbage.
Your later mallocs are to fill pointers in your structure. The memory is NOT put there, it is put wherever the OS wants it, and your pointer points to it. You have to allocate memory to hold the structure that has the pointers. Then you have to have a pointer to point to that memory. So, yes. You have to allocate memory for your structure. Now, had you done this: Code:
int main (int argc, char *argv[]){ In that case, to access an element of the structure, you'd use the syntax Mem_Man.Mem_Chunk_Used. To point to the structure so you could pass the pointer to a subroutine, you'd use the syntax &Mem_Man. |
Quote:
In this analogy system memory allocator is the entity cutting out the trees in the forest. It also makes accounting, i.e. it won't allow somebody else to cut out the same piece of forest and build on it. Also, the system memory allocator knows how much forest to be cut out at all exists - any single person can't have more forest cut out then total forest area. The house with its walls, floors, stairs, etc. is you structure - the allocator doesn't care about the internals, it cares about total area of you lot. |
Quote:
The usual way to code that would be Code:
int main (int argc, char *argv[]){ Then, when you pass it to a function such as mm_init, you pass the address of the object, rather than the value of a pointer. Note the & I used above. This method does require the extra & each place you pass it to a function and means main() accesses the members differently than every other function, for example: In main Mem_Man.Mem_Chunk vs. in any other function MM->Mem_Chunk If those syntax issues bother you, you could make both a pointer and an object Code:
int main (int argc, char *argv[]){ If the desired duration of the object were not the same as the duration of main(), that is the case in which it is best to use malloc: Code:
int main (int argc, char *argv[]){ |
Quote:
The beauty of stack allocation is that it takes no time and typically doesn't need operations similar to 'free'. |
Good good good. Thanks all again!
|
All times are GMT -5. The time now is 09:53 PM. |