I am new to c...so kindly help me in defining a owner for a memory
It's all a conceptual notion so you can blurr or ignore it whatever you want. An owner
creates and/or deletes allocated memory when it doesn't expose it to others or
when the others just use the memory, as in:
-
char* f() {
-
char* cp= malloc(42);
-
/* do something with cp[0], cp[1], ... */
-
g(cp); * expose it to something else */
-
/* but keep ownership */
-
/* do something with cp[0], cp[1], ... */
-
return cp; /* pass ownership to something else */
-
}
-
void g(char* cp) {
-
/* do something with the memory but don't release it */
-
/* do something with cp[0], cp[1], ... */
-
/* g() is not the owner of it */
-
}
-
void h() {
-
char* cp= f();
-
/* now h() is the owner of the memory */
-
/* do something with cp[0], cp[1], ... */
-
/* so if it's done with it, release it */
-
free(cp);
-
}
-
In this little scenario f() was the owner of the memory but it gave ownership of it
to function h() when it returned; h() frees the memory at the end because it was
the new owner of it; function g() just used the memory so it doesn't free it because
it wasn't the owner.
In C you have to keep track of the 'ownership' yourself; C allows you to shoot
yourself in the foot big times when you don't take care. In the example above it
may seem trivial but in larger real world code things might get tricky. Keeping
track of that ownership might help you to keep things organized.
kind regards,
Jos