I am new to C
and the main differences with other languages in which I am more advanced is the use of memory.
I am doing the following exercise:
Given the definition of T in the Th file, it is proposed to implement: T_mdfyTitle(): Modifies the data of type T received as a parameter, with a new name. Note: Correct memory management must be performed.
being T
:
typedef struct {
char* name;
int code;
} T;
For me in Java or C# it would be as simple as a setter, so I've implemented:
tError T_mdfyTitle(T* object, const char* newName){
object->name=newName;
return OK;
}
Now... when I reread:
Note: Correct memory management must be performed.
I think I'm not doing something right. Does my code correctly manage memory? And going further, when do I know that I have to manage memory?
As a broad answer to that broad question, if your code uses pointers you may have to manage memory.
Coming from Java and C# you will be familiar that classes that handle strings are invariant in those languages. In other words, when you concatenate two strings in these languages, you do not modify one of the strings, but rather a new one is generated:
The C language does not have these mechanisms: it handles raw memory. To store a string of characters you must request memory to accommodate all the characters of that string plus an additional one (to mark the end of the string with the null character
'\0'
), so following the previous example:Concatenation target variable has no memory allocated
malloc
).strcpy
).strcat
).malloc
we must release it withfree
.As you can see, each string lives in a memory space pointed to by a pointer, so in your implementation:
You are copying the pointer (not the pointed content). This is not an error a priori if it is your intention, but if the original string (the one pointed to by the argument
newName
) disappears, theobject->name
will be pointing to invalid memory. The correct memory management would be:newName
withstrlen
.'\0'
) aboutobject->name
withmalloc
.newName
into the memory pointed to byobject->name
withstrcpy
ormemcpy
.T
, it must be freedfree
over its pointername
.