I’m working my way in understanding pointers. I wrote this string copy functionality in C.
#include<stdio.h>
char *my_strcpy(char *dest, char *source)
{
while (*source != '\0')
{
*dest++ = *source++;
}
*dest = '\0';
return dest;
}
int main(void)
{
char* temp="temp";
char* temp1=NULL;
my_strcpy(temp1,temp);
puts(temp1);
return 0;
}
This program gives a segfault.If I change char* temp1=NULL to char* temp1 still it fails. If I change char* temp1 to char temp1[80], the code works. The code also works if char temp1[1] and gives the output as temp. I was thinking the output should be t. Why is it like this and why do I get error with char* temp.
Because you’re not allocating space for the destination string. You’re trying to write to memory at position
NULL(almost certainly0x00).Try
char* temp1= malloc(strlen(temp)+1);or something like it. That will allocate some memory and then you can copy the characters into it. The +1 is for the trailing null character.If you wrote Java and friends, it would prevent you from accessing memory off the end of the array. But at a language level, C lets you write to memory anywhere you want. And then crash (hopefully immediately but maybe next week). Arrays aren’t strictly enforced data types, they are just conventions for allocating and referencing memory.
If you create it as
char temp1[1]then you are allocating some memory on the stack. Memory near that may be accessible (you can read and write to it) but you will be scribbling over other memory intended for something else. This is a classic memory bug.Also style: I personally advise against using the return values from
++s. It’s harder to read and makes you think twice.Is clearer. But that’s just my opinion.