Reputation: 67
#include<stdio.h>
#include<stdlib.h>
char* concatenate(char a[],char b[])
{
int length1,length2,i,j,k,l;
for(int i=0;a[i]!='\0';i++)
{
length1=i;
}
for(int j=0;b[j]!='\0';j++)
{
length2=j;
}
char *allocate=(char*)malloc((length1+length2+2)*sizeof(char));
for(k=0;k<=length1;k++)
{
allocate[k]=a[k];
}
allocate[k]=' ';
for(l=length1+2;l<=(length1+length2+2);l++)
{
allocate[l]=b[l-(length1+2)];
}
allocate[l]='\0';
return allocate;
}
int main()
{
char name1[]="Stack";
char name2[]="Overflow";
char* new=concatenate(name1,name2);
printf("%s\n",new);
free(new);
new=0;
return 0;
}
Hi ,I wrote a program to concatenate two strings with the help of malloc concept.I got it correct.But what i didn't get is when i changed the below line
char *allocate=(char*)malloc((length1+length2+2)*sizeof(char));
to
char *allocate=(char*)malloc(sizeof(char));
the output remain same, how is that even possible,because we need atleast length1+length2+2 bytes to store it with gap?
Upvotes: 0
Views: 65
Reputation:
char *allocate=(char*)malloc(sizeof(char));
is the same as
char *allocate=malloc(1);
You allocate exactly one byte of memory, this could only hold the empty string, because it only consists of the terminating 0
byte.
C won't stop you if you write beyond the bounds of your object. This is just undefined behavior. The outcome could be anything, including a program that seems to work. But the next day, or with some other input, it could crash, allow intruders on your system, or even paint your cat green. Just avoid undefined behavior.
Upvotes: 2
Reputation: 61984
There are two possibilities:
Either your runtime environment allocates more memory than necessary, so your "Stack Overflow\0" string fits, but "Stack Overflooooooooooooow\0" would not fit, or
You are corrupting memory past the block that you allocated, and the C runtime environment does not take notice, because your program is trivial. However, if your program was slightly more complicated, (say, if you tried to allocate more memory,) you would get an error.
Upvotes: 2