I am new to C programming and I am unable to figure out why this is happening.
char *example(char *temp) {
char *xyz;
memset(xyz,0,strlen(temp));
strncpy(xyz,temp,3);
strcat(xyz,"XX);
return xyz;
}
int main() {
char temp[] = "ABCDEF"
char *xyz;
xyz = example(temp);
printf("Returned string is: %s",xyz);
return 0;
}
I just want to know what all I am doing wrong cause I tried to run GDB and it showed I am trying to access some unreachable part of memory but am not able to figure it out. Thanks in advance.
The problem is here:
You never initialized
xyz. Therefore it’s an invalid pointer.What you need to do it allocate something for it:
and free it when you’re done with it:
EDIT : Other problems:
These 3 lines here are very dangerous: