I don't understand it prints out OneExample when i allocated memory for 5. I know it is possible to do it using strncpy But is there a way to do it without using strncpy
It works with strncpy, but is there a way to do it without strncpy ?
void main()
{
char *a;
a=(char*)malloc(5);
a="OneExample";
printf("%s",a);
free(a);
}
It prints out OneExample
Should not it print OneE ?? Can someone explain ?
void main()
{
char *a;
a=(char*)malloc(5);
a="OneExample";
printf("%s",a);
free(a);
}
You aren't using the memory you've allocated. After allocating the memory, you override the pointer a
with a pointer to a string literal, causing a memory leak. The subsequent call to free
may also crash your application since you're calling free
on a pointer that was not allocated with malloc
.
If you want to use the space you allocated, you could copy in to it (e..g, by using strncpy
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With