-1

I'm trying to recode the function strcat featuring an auto-malloc inside it. I can see in few tests that there are some data leaks (I don't know the correct word) in my function.

Here's my code :

char    *my_strcat(char *a, char *b)
{
  char  *result;
  int   i;
  int   j;
  int   la;
  int   lb;

  la = -1;
  lb = -1;
  while (a[++la] != '\0');
  while (b[++lb] != '\0');
  result = malloc(sizeof(char) * (la + lb) + 1);
  i = -1;
  while (a[++i] != '\0')
    result[i] = a[i];
  j = -1;
  while (b[++j] != '\0')
    result[i + j] = b[j];
  result[i + j] = '\0';
  return (result);
}

So when I try to use my my_strcat in a while loop with some one-length strings I get a :

a.out: malloc.c:2392: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
Aborted (core dumped)

I'm trying to find where my memory leak comes from. But I can't figure out.

Here's the calling part :

while (!is_line_ended(read_result))
{
  read(fd, read_result, READ_SIZE);
  result = my_strcat(result, read_line(read_result, fd));
}

Here's MY_STRLEN :

# define MY_STRLEN(s) (sizeof(s)/sizeof(s[0]))

Please notice that I'm limited to one file and one header. I'm limited to 5 functions by file, and I'm not allowed to use string functions.

mch
  • 9,424
  • 2
  • 28
  • 42
Orionss
  • 725
  • 2
  • 10
  • 26

1 Answers1

1

The problem is your macro # define MY_STRLEN(s) (sizeof(s)/sizeof(s[0])):

sizeof(s) does not return the string length of s but rather the size of s's type, i.e. sizeof(char*).

Use strlen(s) instead of your macro; and if - for any reason - you are not allowed to use strlen, you could use the following function:

int my_strlen(const char* s) {
  int len=0;
  while (*s++ != '\0')
    len++;
  return len;
}
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58