user1169094
user1169094

Reputation: 157

what will happen if i don't free a pointer before allocating it

i am making a custom copy function like this:

  if (s1 == NULL || s2 == NULL || s2->buf == NULL)
    return;

  if (s1->len + 1 < s2->len + 1)
    {
      if (s1->buf)
        free (s1->buf);

      s1->buf = (char *) malloc (s2->len + 1);
      if (s1->buf == NULL)
      return;
    }

  for (int i = 0; i < s2->len; i++)
    s1->buf[i] = s2->buf[i];

  s1->len = s2->len;

where as s1 and s2 are simply struct pointers that have a char pointer and an unsigned integer in them.

  if (s1->len + 1 < s2->len + 1)
    {
      if (s1->buf)
        free (s1->buf);

      s1->buf = (char *) malloc (s2->len + 1);
      if (s1->buf == NULL)
      return;
    }

this will check to see if there is enough space inside of the s1 to fit for s2. if there isn't, it will then check for existing memory and free it. after that is done, it will allocate a new memory block for s1, which is the size of s2 + 1 (include \0).

here is where i am confused

if there is enough space in the char pointer for s2 to fit into s1 (including \0) and it doesn't free() and call malloc() again, it just assigns with the for loop, will it keep the original contents of s1?

Upvotes: 0

Views: 269

Answers (1)

cnicutar
cnicutar

Reputation: 182619

if there is enough space in the char pointer for s2 to fit into s1 (including \0) and it doesn't free() and call malloc() again, it just assigns with the for loop, will it keep the original contents of s1?

If there is enough space you don't need to free or malloc again. Just hold on to the allocated chunk.

Calling malloc isn't something special: it simply gives you a pointer where you can start storing data. If you already have that pointer, great.

Upvotes: 1

Related Questions