I need something like strlen
but the string is filled with only null-terminators "\0\0\0\0\0\0\0"
and I need to fill it with another character up until (not including) the last \0
like so "FFFFFF\0"
. Is there a way to calculate the size without errors?
I had to implement bzero
for a school project called "libft". Then I was tasked with implementing strcpy
and I saw in the man pages that dest
needs to be large enough to receive the copy of src
so I want to account for a situation where bzero
was used on dest
and strcpy
doesn't allow me to pass the size of dest
as a parameter. I was just wondering (out of curiosity) how I would know how big dest
is because I know that strcpy
does not account for this. There is a warning in the man page "Beware of buffer overruns! (See BUGS.)".
I realise now that this might be impossible in C.
What you're asking is whether you can know how much memory has been allocated.
If it was allocated with malloc
, no.
If it's an array allocated on the stack, like char foo[10]
, yes you can use sizeof(foo)
, but that doesn't tell you anything you didn't already know.
If you need to know the allocated size of the string, you need to remember it at allocation time and pass it around. You can use an extra variable, or you can make a struct
which has both the string and size.