I would like to actually use this wrapper, but the problem is i don’t know if it’s very safe, yet.
I have a few simple questions regarding using malloc(), calloc(), and realloc(). Here’s what I have so far:
string.h
typedef struct str str; // pointer for encapsulation
string.c
struct str
{
char *buf;
size_t len;
}
Say i have a helper function that simply does this:
str *NEW_STRING()
{
str *temp = calloc(1, sizeof (struct str));
temp->len = 0;
temp->buf = (char *) malloc(1);
return temp;
}
Is this safe? If it is, what would happen if i did something like this:
str *A_STRING = NEW_STRING();
A_STRING = NEW_STRING();
It would call malloc and calloc twice, is that bad? Would an initializer be better?
void str_init(str *A_STRING)
{
if (A_STRING)
{
free(A_STRING);
}
if (A_STRING->buf)
{
free(A_STRING->buf);
}
A_STRING = calloc(1, sizeof (struct str));
A_STRING->buf = (char *) malloc(1);
A_STRING->len = 0;
}
Finally, is this a good way to free memory?
void free_string(str *A_STRING)
{
if (A_STRING->buf)
{
free(A_STRING->buf);
}
else
{
A_STRING->buf = NULL;
}
if (A_STRING)
{
free(A_STRING);
}
else
{
A_STRING = NULL;
}
A_STRING->len = 0;
}
Any additional information would be great if included. I don’t want to release anything to the public as if it were a good library, because i am primarily doing this for learning purposes.
Lots of errors:
No.
Next:
You leak memory.
The second call basically generates a new object the old object is lost and leaks.
Problems in str_init
Is this the first time that his method is called?
If so then A_STRING contains a random value (that you are about to FREE).
This will blow the code up.
A_STRING is freed (you can now no longer accesses it).
Any code that does so is bad.
No checking the result of calloc.