#include<stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char *str = (char*)malloc(4);
strcpy(str,"aaab");
char *pt;
strcpy(pt,str);
while(pt != NULL){
printf("%c",*pt);
pt++;
}
}
I wanted this code to just print out the str string but instead it gave me the string and some bizzare output.The thing just gets better as the pattern keeps changing. I think the problem is with null character '\0' termination.
This only allocated memory for the pointer. The contents of the pointer are indeterminate, i.e. they may be pointing to anything and accessing the memory pointed to by the pointer invokes undefined behaviour. You need to allocate memory for the pointed-to data before trying to copy something to it.
Do not cast the result of
malloc().malloc()and family returns a genericvoid *that is implicitly converted to any other pointer type. The cast is redundant and just clutters the code.Check the return value of
malloc(). It returns aNULLpointer constant to indicate failure.Compare
p's pointee to the null-byte, not theNULLpointer constant.Or simply;
Otherwise, your code would invoke undefined behaviour.