There are several problems with the shown code.
The first one is that the string literal "aaab"
contains 5
characters (including the terminating zero character '\0'
) instead of 4
. So the call of strcpy
that expects as the second argument a pointer to a string
char *str = (char*)malloc(4);
strcpy(str,"aaab");
invokes undefined behavior because the destination dynamically allocated memory is not large enough to store 5
characters.
You need to allocate one more byte to store the string
char *str = (char*)malloc(5);
In this code snippet
char *pt;
strcpy(pt,str);
there is used the uninitialized pointer pt
and as a result again the call of strcpy
invokes undefined behavior.
You could write for example
char s[5];
char *pt = s;
strcpy(pt,str);
And this while loop has undefined behavior even if the pointer pt
would be initialized
while(pt != NULL){
printf("%c",*pt);
pt++;
}
Instead you should compare not the pointer itself with NULL
but the character pointed to by the pointer with the terminating zero character '\0'
like
while(*pt != '\0'){
printf("%c",*pt);
pt++;
}
Of course the pointer pt
shall point to a string.
Pay attention that you should free the allocated memory when it is not required any more
free( str );