You have allocated many times more than you need. (sizeof(int)
times to be precise). The correct would be
#define MAXLEN 10
...
str = malloc(sizeof *str*(MAXLEN+1));
Note that this will be sizeof(char)
which is 1
. So you can do this also
str = malloc(MAXLEN+1);
Check the return value of malloc
as shown below: (malloc
might not be able to service the request, it might return a null pointer. It is important to
check for this to prevent later attempts to dereference the null pointer).
str = malloc(MAXLEN+1);
if(!str){
perror("malloc");
exit(EXIT_FAILURE);
}
Also void*
to char*
conversion is implicit - you don't need to cast the return value of malloc
.
sizeof(*str)
is a cleaner way to get the size of the type of the element for which we are allocating memory in str
. The benefit is when you are later changing the code and making str
point to an allocated memory which will contain int
-s you don't need to look for sizeof(char)
and then replace it with sizeof(int)
it is done here by using sizeof(*str)
automatically.