It is printing everything but it terminating ...
Consider your memory allocation statements:
char *a;
a=(char *)malloc(sizeof(char));
By allocating only sizeof(char)
bytes to the buffer a
, then attempting to write anything more than the null terminator to it, you are invoking undefined behavior. (Note: sizeof(char)
in C is by definition equal to 1
, always)
C strings are defined as a null terminated character array. You have allocated only one byte. The only legal C string possible is one containing only the null termination byte. But your code attempts to write much more, and in so doing encroaches on memory locations not owned by your process. So in general, when creating strings, follow two simple rules:
- Determine
max length
of string you need
- allocate memory to
max length + 1
bytes to accommodate termination byte.
Example if max string is x
characters long, create the memory for x + 1
characters:
char inputStr[] = {"This string is x char long"};
char string = malloc(strlen(inputStr) +1); //+1 for null byte
strcpy(string, inputStr);
Note, in C it is not recommended to cast the return of malloc() and family.