Reputation: 31
I was implementing string copy function using character pointers but it is showing error. Here is the code:
#include<stdio.h>
#include<string.h>
int main()
{
char *s="abc";
char *t;
while((*s)!='\0')
{
*t++=*s++;
}
*t='\0';
printf("%s\n",t);
return 0;
}
Upvotes: 1
Views: 122
Reputation: 719
This might result in a segmentation fault
The reason being : Just think where is char *t
pointing to right now?
Let's have a look at the possibilities :
1.Your char *t
is pointing to some memory location which can not be accessed or write-protected;
2.It might work in some cases where your pointer is pointing to a memory location that can be accessed and has required space.The possibilities of that being very small.
So, it's better to use
char *t=NULL;
t=malloc(sizeof(char)*n); //Dynamic approach
here n is the no of bytes you are allocating to t
If you're not comfortable with dynamic memory allocation right now
reserve some space for t
which you think is enough. This will waste some space though.
After you're done, free the space allocated;
free(t);
Note : Always include <stdlib.h>
else malloc will result in a warning.
Upvotes: 1
Reputation: 19864
char *t;
There is no memory allocated to your pointer and you are trying to write to it which will lead to undefined behavior.So allocate memory
char *t = malloc(30); /* size of your choice or strlen(s) + 1*/
Once done using the memory free it using
free(t);
Upvotes: 7