Using malloc to allocate string

Hello there,
In this code below, even if i put 1 or any number as argument in the malloc function, the result is always correct, no matter what. But if i remove it, result is unreadable. What happen with malloc?

The program concatinates 2 strings.
EDIT: I use gcc on Ubuntu

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 20

char* my_strcat(char*, char*);

int main()
{
  char str1[N], str2[N], *str3;

  printf("\nInput the first string: ");
  scanf("%s", str1);
  printf("Input the second string: ");
  scanf("%s", str2);
  str3 = my_strcat(str1, str2);
  printf("The concatenated string is: %s\n", str3);

  return 0;
}

char* my_strcat(char* str1, char* str2)
{
  char* str3;
  int i, iLength1, iLength2;

  iLength1 = strlen(str1);
  iLength2 = strlen(str2);

  str3 = (char*) malloc(strlen(str1) + strlen(str2) + 1);
  for (i = 0; i < iLength1; i++)
    {
      str3[i] = str1[i];
    }
  for (i = 0; i < iLength2; i++)
    {
      str3[i + iLength1] = str2[i];
    }

  return str3;
}
Last edited on
malloc probably get more memory from the OS than it actually needs (the extra memory can be used for later allocations) so that's probably why reading and writing outside the limit of what you requested doesn't crash.

EDIT: one problem with your program is that you forgot to place a null termination character at the end of the new string.
Last edited on
Topic archived. No new replies allowed.