I have the following struct:
typedef struct cell Cell;
struct cell {
int value;
int *nextcell;
};
And I have the following function to free a linked list:
void freelist(Cell *beginning)
{
Cell *thisCell = beginning;
Cell *NextCell = beginning->nextcell;
while (thisCell != NULL)
{
NextCell = thisCell->nextcell;
free(thisCell);
thisCell = NextCell;
}
/* Here comes my question. Do I need to free the following variables? */
free(beginnig);
free(thisCell);
free(NextCell);
}
No, freeing is intended for the dynamically allocated memory, a pointer is just a variable that points there. Your loop frees all the memory the list took - at that point there's nothing to free and trying to free the same memory again (beginning) would result in an error. thisCell after the loop is NULL there there's not even something to free there.
If you meant the pointers themselves, they did not allocate memory dynamically, when you defined them they each took a slot on the stack, and leaving the function would release that slot. Here we're only talking about the pointers themselves (the place where the address they point to is stored), not the pointed memory they might hold.
You free memory that you allocate no matter where the pointer is stored - in a local variable, in a global / static variable, or in a pointer that is allocated on the free store itself.
Your function frees several pointers multiple times: you do not need any of the three calls to free at the bottom of your function (although the second call is harmless, because it passes NULL to free, which is always OK).
Related
Could someone please explain to me the difference between creating a structure with and without malloc. When should malloc be used and when should the regular initialization be used?
For example:
struct person {
char* name;
};
struct person p = {.name="apple"};
struct person* p_tr = malloc(sizeof(struct person));
p_tr->name = "apple";
What is really the difference between the two? When would one approach be used over others?
Having a data structure like;
struct myStruct {
int a;
char *b;
};
struct myStruct p; // alternative 1
struct myStruct *q = malloc(sizeof(struct myStruct)); // alternative 2
Alternative 1: Allocates a myStruct width of memory space on stack and hands back to you the memory address of the struct (i.e., &p gives you the first byte address of the struct). If it is declared in a function, its life ends when the function exits (i.e. if function gets out of the scope, you can't reach it).
Alternative 2: Allocates a myStruct width of memory space on heap and a pointer width of memory space of type (struct myStruct*) on stack. The pointer value on the stack gets assigned the value of the memory address of the struct (which is on the heap) and this pointer address (not the actual structs address) is handed back to you. It's life time never ends until you use free(q).
In the latter case, say, myStruct sits on memory address 0xabcd0000 and q sits on memory address 0xdddd0000; then, the pointer value on memory address 0xdddd0000 is assigned as 0xabcd0000 and this is returned back to you.
printf("%p\n", &p); // will print "0xabcd0000" (the address of struct)
printf("%p\n", q); // will print "0xabcd0000" (the address of struct)
printf("%p\n", &q); // will print "0xdddd0000" (the address of pointer)
Addressing the second part of your; when to use which:
If this struct is in a function and you need to use it after the function exits, you need to malloc it. You can use the value of the struct by returning the pointer, like: return q;.
If this struct is temporary and you do not need its value after, you do not need to malloc memory.
Usage with an example:
struct myStruct {
int a;
char *b;
};
struct myStruct *foo() {
struct myStruct p;
p.a = 5;
return &p; // after this point, it's out of scope; possible warning
}
struct myStruct *bar() {
struct myStruct *q = malloc(sizeof(struct myStruct));
q->a = 5;
return q;
}
int main() {
struct myStruct *pMain = foo();
// memory is allocated in foo. p.a was assigned as '5'.
// a memory address is returned.
// but be careful!!!
// memory is susceptible to be overwritten.
// it is out of your control.
struct myStruct *qMain = bar();
// memory is allocated in bar. q->a was assigned as '5'.
// a memory address is returned.
// memory is *not* susceptible to be overwritten
// until you use 'free(qMain);'
}
If we assume both examples occur inside a function, then in:
struct person p = {.name="apple"};
the C implementation automatically allocates memory for p and releases it when execution of the function ends (or, if the statement is inside a block nested in the function, when execution of that block ends). This is useful when:
You are working with objects of modest size. (For big objects, using many kibibytes of memory, malloc may be better. The thresholds vary depending on circumstances.)
You are working with a small number of objects at one time.
In:
struct person* p_tr = malloc(sizeof(struct person));
p_tr->name = "apple";
the program explicitly requests memory for an object, and the program generally should release that memory with free when it is done with the object. This is useful when:
The object must be returned to the caller of the function. An automatic object, as used above, will cease to exist (in the C model of computation; the actual memory in your computer does not stop existing—rather it is merely no longer reserved for use for the object) when execution of the function ends, but this allocated object will continue to exist until the program frees it (or ends execution).
The object is very large. (Generally, C implementations provide more memory for allocation by malloc than they do for automatic objects.)
The program will create a variable number of such objects, depending on circumstances, such as creating linked lists, trees, or other structures from input whose size is not known before it is read.
Note that struct person p = {.name="apple"}; initializes the name member with "apple" and initializes all other members to zero. However, the code that uses malloc and assigns to p_tr->name does not initialize the other members.
If struct person p = {.name="apple"}; appears outside of a function, then it creates an object with static storage duration. It will exist for the duration of program execution.
Instead of struct person* p_tr = malloc(sizeof(struct person));, it is preferable to use struct person *p_tr = malloc(sizeof *p_tr);. With the former, a change to the p_tr requires edits in two places, which allows a human opportunity to make mistakes. With the latter, changing the type of p_tr in just one place will still result in the correct size being requested.
struct person p = {.name="apple"};
^This is Automatic allocation for a variable/instance of type person.
struct person* p_tr = malloc(sizeof(person));
^This is dynamic allocation for a variable/instance of type person.
Static memory allocation occurs at Compile Time.
Dynamic memory allocation means it allocates memory at runtime when the program executes that line of instruction
Judging by your comments, you are interested in when to use one or the other. Note that all types of allocation reserve a computer memory sufficient to fit the value of the variable in it. The size depends on the type of the variable. Statically allocated variables are pined to a place in the memory by the compiler. Automatically allocated variables are pinned to a place in stack by the same compiler. Dynamically allocated variables do not exist before the program starts and do not have any place in memory till they are allocated by 'malloc' or other functions.
All named variables are allocated statically or automatically. Dynamic variables are allocated by the program, but in order to be able to access them, one still needs a named variable, which is a pointer. A pointer is a variable which is big enough to keep an address of another variable. The latter could be allocated dynamically or statically or automatically.
The question is, what to do if your program does not know the number of objects it needs to use during the execution time. For example, what if you read some data from a file and create a dynamic struct, like a list or a tree in your program. You do not know exactly how many members of such a struct you would have. This is the main use for the dynamically allocated variables. You can create as many of them as needed and put all on the list. In the simplest case you only need one named variable which points to the beginning of the list to know about all of the objects on the list.
Another interesting use is when you return a complex struct from a function. If allocated automatically on the stack, it will cease to exist after returning from the function. Dynamically allocated data will be persistent till it is explicitly freed. So, using the dynamic allocation would help here.
There are other uses as well.
In your simple example there is no much difference between both cases. The second requires additional computer operations, call to the 'malloc' function to allocate the memory for your struct. Whether in the first case the memory for the struct is allocated in a static program region defined at the program start up time. Note that the pointer in the second case also allocated statically. It just keeps the address of the memory region for the struct.
Also, as a general rule, the dynamically allocated data should be eventually freed by the 'free' function. You cannot free the static data.
I'm trying to create a memory allocation system, and part of this involves storing integers at pointer locations to create a sort of header. I store a couple of integers, and then two pointers (with locations to the next and prev spots in memory).
Right now I'm trying to figure out if I can store the pointer at a location that I could later use as the original pointer.
int * header;
int * prev;
int * next;
...
*(header+3) = prev;
*(header+4) = next;
Then later...
headerfunction(*(header+4));
would perform an operation using the pointer to the 'next' location in memory.
(code for illustration only)
Any help or suggestions greatly appreciated!
Don't do direct pointer manipulation. Structs were made to eliminate the need for you to do that directly.
Instead, do something a bit more like this:
typedef struct
{
size_t cbSize;
} MyAwesomeHeapHeader;
void* MyAwesomeMalloc(size_t cbSize)
{
MyAwesomeHeapHeader* header;
void* internalAllocatorPtr;
size_t cbAlloc;
// TODO: Maybe I want a heap footer as well?
// TODO: I should really check the following for an integer overflow:
cbAlloc = sizeof(MyAwesomeHeapHeader) + cbSize;
internalAllocatorPtr = MyAwesomeRawAllocator(cbAlloc);
// TODO: Check for null
header = (MyAwesomeHeapHeader*)internalAllocatorPtr;
header->heapSize = cbSize;
// TODO: other fields here.
return (uint8_t*)(internalAllocatorPtr) + sizeof(MyAwesomeHeapHeader);
}
What-ever you are doing is not safe because you are trying to write a memory location which is not pointed by header as *(header+3) it will try to write to some other memory location 12 byte far from header pointer & if this newly memory is held by another variable then it will cause problem.
You can do as first of all allocating a big memory & then the start address will give you the source of your memory in which you can use some starting bytes or memory for controlling other parts of the remaining memory with the help of structures.
Akp is correct, just looking at what you are trying to accomplish in your code segment, if you are trying to store integer pointers in header, header should be defined as such:
int **header;
and then memory should be allocated for it.
With regards to the actual memory allocation, if on a Unix machine, you should look into the brk() syscall.
You are building a memory allocation system, and thus we assume you have a trunk of memory somewhere you can use freely to manage allocations and freeings.
As per your question, the header pointer is allocated in the heap memory (by the compiler and libraries) - and you may wonder if it is safe to use that memory since you are allocating memory. It depends on your system, and if there is another (system) memory allocation management.
But what you could do is
main() {
void *header;
void *prev;
void *next;
manage_memory_allocations(&header, &prev, &next); // never returns
}
In this case, the pointers are created on the stack - so the allocation depends on the memory where the processor stack points to.
Note the "never returns" as the memory is "freed" as soon as main ends.
I'm sure it doesn't, but maybe there's black magic in it, so here's my question:
If I have a struct like this:
struct mystr {
char * strp,
unsigned int foo,
};
and I allocate memory for it and want to release it later. Do I have to do
free(mystr_var->strp);
free(mystr_var);
or is the last line enought, does the free() function follow the pointers and free them two?
No, free doesn't follow pointers, you need both lines.
I usually write a function like:
void freemystr(mystr *mystr_var)
{
if (mystr_var)
{
free(mystr_var->strp);
mystr_var->strp = NULL;
free(mystr_var);
}
}
Every individually allocated block of memory must be freed individually. free() will only free the memory block that the pointer points to and its has no knowledge of what is the content of that memory.
Hence, in your case you are doing it the right way by first freeing the innermost memory allocated in a structure and finally freeing the struct pointer.
If you just do free on the struct pointer, the struct memory gets freed. The memory held by char* strp, becomes a memory leak in your program lifetime.
No, it doesn't.
It's not magic at all, to the compiler it's just another function call.
Ask youself how you would implement void free(void *); in a way that follows pointers, of course without being fooled by being given a binary data block containing anything. You can't.
No. It simply frees the block pointed to.
You need to explictly free referenced memory. You need to do this first (i.e. most likely in the opposite direction to how you allocated the memory)
No. free won't do recursive free for all members. You have to explicitly free all members for which you have allocated memory.
If you understand how memory is allocated for struct and how free works this won't be a problem.
struct mystr {
char * strp,
unsigned int foo,
};
when you allocated memory using malloc & friends, it only allocates memory for the members.
In your case one char* and one unsigned int. Note that it doesn't allocate any memory for storing data in the char*. So you have to allocate memory for strp again before storing data. Except when you directly assign string literals Or just use the pointer strp to point to an existing memory.
Example:
case 1:
struct mystr s;
s.strp = "literals"; // valid, no need to malloc
case 2:
char *p="abc";
s.strp = p; // valid, no need to malloc
On all other usages, you must allocate memory for strp before storing data into strp.
So when you call free on the struct variable, it only frees the pointer allocated for strp and not the memory which is pointed to by strp.
It's simply because free has no information about where strp points to.
Note that in the above two examples, you don't free strp as you didn't allocate any memory there for storing data into strp. Simple rule is one free for one malloc/calloc/realloc.
C99 says,
The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.
I've read conflicting information on the internet about this. To the best of my knowledge all variables in a function only exist for the life time of the function and so this shouldn't be necessary. But with dynamic pointer arrays I'm not sure.
Thanks
You don't free pointers - they are cleaned up automatically. What you need to free is the memory that was acquired by malloc. You use pointers to access that memory.
Put laconically: Every pointer you get from malloc has to go to free exactly once. Nothing more, nothing less.
It depends on where the memory referenced by the pointer has been allocated.
There are fundamentally 2 ways of allocating space in C.
Using the stack :
void foo(){
int stack_variable = 10;
int *stack_pointer = &stack_variable; //bar shouldn't be freed.
}
Using the heap:
void foo(){
int * heap_pointer = (int *) malloc(sizeof(int)); //heap_pointer need to be freed somewhere
}
In the first case there is no problem: memory allocated in the stack will be released when the function returns. Even if you are using a pointer, and it points to some data in the stack, free isn't necessary. Be careful to not use a pointer to data allocated in the stack when the data itself goes out of scope:
int * foo(){
int stack_variable = 10;
int *ptr = &stack_variable;
return ptr;
}
int * ptr = foo(); // you have a problem here: ptr points to a memory region that no longer exist!
In the second case you are using the heap so you need to use free somewhere, to explicitly release it.
If you have allocated data using malloc/calloc, you need to free the data.
Addition due to curious comment by #Julia Childe:
Well, the point of allocating dynamic memory is that it will remain there till you explicitly free it. This enables you to pass pointers both from and to functions and you are not limited by the scope of a specific function, i.e. main.
Thereby, you can allocate memory for data when you need to and not in advance, thus dynamic memory.
If we did not have this ability, we would have to know how much memory space we would use at compile time.
Hope this clears out some question marks.
I am a java programmer learning C. Have a question regaring functions. What are the differences between this:
main()
{
struct person myperson;
myperson = myfunction();
return;
}
struct person myfunction()
{
struct person myPerson;
myPerson.firstname = "John";
myPerson.lastname = "Doe";
return myPerson;
}
VS
main()
{
struct person *myperson;
myperson = myfunction();
return;
}
struct person* myfunction()
{
struct person *myPerson;
myPerson = malloc(sizeof(struct person));
myPerson->firstname = "John";
myPerson->lastname = "Doe";
return myPerson;
}
Are these legal in C? And y would 1 choose one over the other.
Thanks so much guys!
first code sample:
you create a struct in myfunction() on your stack and return it. then, you create another stack struct, and you copy the first to the second. the first is destroyed. the second will be automatically destroyed when you are out of the scope.
2 structs were actually created.
second code sample:
you create a struct in myfunction(), and then you copy only the address. the struct in main will actually be the same struct.
only one struct is created in here.
both code samples work, but for the later you will have to explicitly free the memory allocated for the struct, to avoid memory leak, but performance should be better since you don't need to copy the struct!
EDIT:
as mentioned by #Mat: this of course neglects the overhead of malloc(), which is not true for small structs.
The first version allocates the object on the stack and returns a copy of it. The second version creates the object on the heap and returns a pointer to it(this is closest to Java references except that the memory isn't automatically freed). You should not forget to call free() later on the returned pointer.
Btw, your main function is bad. It should be
int main(void)
{
...
return 0;
}
I suggest that you should read a good C book. This is really basic stuff you're asking.
I'm not sure if all this talk of "heap" and "stack" is cutting to the core of the language, so let me try something more language-intrinsic.
Your first version uses only automatic allocation, which means that all variables have automatic lifetime. That is, all variables end their life at the end of their enclosing scope: myFunction creates a local variable of type struct person and returns a copy of that variable; the main function declares a local variable of the same type and assigns to it the result of the function call. At the end of each scope, the local variables end as well.
The second version uses dynamic or manual allocation. You explicitly allocate storage for a person variable with the malloc() call, and that storage will remain allocated until someone deallocates is (via free()). Since you never deallocate it, this is in effect a memory leak.
The fundamental difference is one of lifetime and responsibility.
A few pros and cons: Automatic allocation means that responsibility is local, and you generally don't have to worry about anything. However, it comes at the price of having to copy arguments and return values by value, which may be expensive or undesirable. Manual allocation allows you to refer to large amounts of memory via a simple, cheap pointer, and is often the only way to implement certain constructions, but carries the burden of having the author remember who's responsible for which resource.
Both are legal, both work.
The 1st version is simpler, you avoid having to deal with memory allocation and releasing.
The 2nd version will perform better for bigger structs because you avoid putting the whole struct on stack for handing it over.
I would actually choose a third way. Let the caller worry about providing storage space (auto or dynamically allocated):
void myfunction(struct person* myPerson)
{
myPerson->firstname = "John";
myPerson->lastname = "Doe";
}
The function can be called either with an automatically or dynamically allocated variable:
struct person autoperson;
myfunction(&person);
struct person dynamic_person = malloc(sizeof struct person);
myfunction dynamic_person);
The first will allocate a struct person on the stack, and pass a copy of it back, then free the original. The second one will allocate it on the heap and pass a pointer to the location which was allocated, and will not free it.
The first one allocates the variables on the stack. The person object from myfunction is copied from the function and returned which is less efficient, but you can't get a memory leak which is good.
The second example returns a pointer (the *) to a person object that is dynamically allocated (with malloc). The person object allocated by malloc will never be destroyed unless you explicitly call free() on it, hwich you haven't - so you have a memory leak.
You need to explicitly free memory in C, it doesn't have garbage-collection like Java.
The first option creates a struct on the stack, when returning it, it gets copied to your struct defined in the main() function. Also copied are the fields. For larger structs this can be a costly operation.
The second option allocates dynamic memory, which does not get copied when you return it. You have to free() the pointer to avoid a memory leak.
Of course it depends on your needs, but for more important and long living objects I'd go for the second option. Also I would recommend to write allocation/initialization functions and a corresponding deallocation function. (see below why)
The problem is that the 2 strings you set in myfunction() are invalid outside of the function, as they are also created on the stack. You have to use strdup() or a similar function to make this failsave. Of course, to not let memory leaks slip in you have to free() the strduped pointers, just as with malloc().
In the first code, myPerson is an object of type struct person that is managed (*) by the implementation itself. In the second code, it is an object of type struct person * (a pointer to a struct person). In the second code, the object itself must be managed by the programmer (malloc, realloc, free).
Also, in the first code, the object itself is copied around a few times whereas in the 2nd code "only" the pointer gets copied. Usualy a pointer is much smaller than an object of a struct type.
Use the 2nd approach but remember to free the object.
Even better, create the object in the parent function and pass a pointer to functions: sruct person *myfunction(struct person *data) { /* ... */ }
(*) with object management I mean the time it gets created and deleted and stuff
First One:
main()
{
// create a person struct on the stack
struct person myperson;
// copy the struct returned by myfunction to myperson.
myperson = myfunction();
}
struct person myfunction()
{
// create a person struct on the stack.
struct person myPerson;
myPerson.firstname = "John";
myPerson.lastname = "Doe";
// return the myPerson struct. After myFunction returns, the memory
// holding the myPerson struct on the stack will be freed.
return myPerson;
}
Second one:
main()
{
// create a pointer to a person struct on the stack
struct person *myperson;
// assign the pointer returned by myfunction to myperson
myperson = myfunction();
}
struct person* myfunction()
{
// create a pointer to a person struct on the stack
struct person *myPerson;
// allocate memory for a person struct in dynamic memory and set myPerson
// to point to that memory. This memory will remain valid until it's freed by
// a call to the "free" function. Using malloc is much slower than creating
// an object on the stack. There is also the added performance cost of
// freeing the allocated memory at a later stage.
myPerson = malloc(sizeof(struct person));
myPerson->firstname = "John";
myPerson->lastname = "Doe";
// return the myPerson pointer
return myPerson;
}