Reputation: 1235
I am fairly new to C programming and still trying to understand all the nooks and crannies of C. I am writing a program to concatenate two strings. But I am getting an error which I don't understand. Here is the output.
Asfakul
The Length of the String name is 7
The Length of the String fullname is 7
L
Segmentation fault (core dumped)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char const *argv[])
{
char *name="Asfakul";
char *surname="Laskar";
char *fullname;
int i=0;
//Allocate Memory of 100 char
fullname=(char*)malloc(100*sizeof(char));
fullname=name;
while(*name !='\0')
{
i++;
name++;
}
// Allocate Memory for FullName
//fullname=(char*)malloc(100*sizeof(char));
//Coppied the spurce String
// fullname=name; // Here this assignement will not work as Pointer name now point to NULL character of String Name.
puts(fullname);
printf("The Length of the String name is %d\n",i );
printf("The Length of the String fullname is %d\n",strlen(fullname) );
while(*surname !='\0')
{
printf("%c\n",*(fullname+i+1));
*(fullname+i+2)=*(surname);
printf("%c\n",*(surname));
i++;
surname++;
}
puts(fullname);
return 0;
}
Please help me understand what I am doing wrong.
Upvotes: 0
Views: 396
Reputation: 7622
You can past char by char
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char const *argv[])
{
char *name="Asfakul";
char *surname="Laskar";
char *fullname;
int i=0;
//Allocate Memory of 100 char
fullname=malloc(100*sizeof(char));
while(*name !='\0')
{
fullname[i++] = *name++;
}
fullname[i] = '\0';
puts(fullname);
printf("The Length of the String name is %d\n",i );
printf("The Length of the String fullname is %zd\n",strlen(fullname) );
fullname[i++] = ' ';
while(*surname !='\0')
{
fullname[i++]= *surname++;
}
fullname[i] = '\0';
puts(fullname);
free(fullname);
return 0;
}
Upvotes: 0
Reputation: 338
*(fullname+i+2)=*(surname);
Here you are trying to cat the surname at the end of the name:
char *name="Asfakul";
This is read-only space.
You should alloc enough space for both strings and copy them inside the allocated space.
Upvotes: 0
Reputation: 234715
fullname = name;
assigns the pointer name
to fullname
. You subsequently modify the data at name
. That's not allowed since name
points to a read-only string literal.
You're also discarding the malloc
pointer, leaving you no way to free
the allocated memory! This will not end well.
You should take a deep copy of name
instead: consider using a strncpy
.
If you were to use const char*
for the string literals then compilation should fail, so protecting yourself from these kind of things.
Upvotes: 6