****EDIT**** : The below post was written before the edit of the question.
You're missing stdlib.h
, to the most, for function malloc()
to work properly. After that,
Point 1:
char *res = (char*)malloc(15*sizeof(char*));
should be
char *res = malloc(15); //will also issue warning to resolve missing stdlib.h
Point no note: you should be allocating memory for char
s, not char *
s. Then , you should write sizeof(char)
, not sizeof(char *)
. Also, sizeof(char)
is always 1 in C
. So, can omit that part.
Please read: do not cast the return value of malloc()
and family in C
.
Point 2:
strings are not supposed to be assigned to already malloc()
ed pointers. use strcpy()
instead.
inp = "hello world";
should be
strcpy(inp, "hello world");
Otherwise, you'll overwrite the previously allocated memory, returned by malloc()
. The assignment will overwrite the memory location held by inp
, causing memory leak.
Point 3.
sizeof()
operator returns a value of size_t
. To print that, you need %zu
format specifier.
Related, from C11
standard document, chapter §7.21.6.1
, paragraph 7,
z
Specifies that a following d, i, o, u, x, or X conversion specifier applies to a
size_t or the corresponding signed integer type argument; or that a
following n conversion specifier applies to a pointer to a signed integer type
corresponding to size_t argument.
Then, to answer the query about the output, in all the cases, you're printing sizeof(inp)
which is essentially sizeof(char *)
and that value is fixed for a particular platform (8
, in your case).
Just FYI, sizeof()
is an operator, it's not a function. It returns the size of the datatype, not the amount of space pointed by the variable.