Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I determine how much valid memory is addressed by a char * argument?

Tags:

c++

c

I have a function like:

// string is a null-terminated char array. Replace all a in the string with b
void ReplaceCharInString(char *string, char a, char b)
{
// loop over the string char by char, to find all "a"s and replace them with "b"
}

I'm doing the defensive programming. The problem is the implementation replies on the client to really pass in an array of chars. If an address of a single char is passed in, the program definitely runs into a bad state(probably crashes). How do I check and avoid this? (I know if I pass in the std::string object, the problem goes away of course)

like image 386
Eric Z Avatar asked Dec 22 '22 21:12

Eric Z


2 Answers

No, you cannot check this and have to trust the user of the function to pass an actual correctly null-terminated string.

This is also the way all the C standard library functions like strcpy(), strlen(), ... work.

like image 55
sth Avatar answered Jan 19 '23 00:01

sth


No you can't check if you're running out of the allocated memory if the string is not null terminated.
As sth said C standard library functions like strcpy(), strlen(), also rely on the fact that the string is valid (null terminated).

... however, one solution could be Mudflap. It is costly (in term of performance) and is only valid with GCC.
Mudflap is a library that instruments all pointer/array operations. With this you will be able to check if a specific location is valid memory or not.

In fact the only reason I see for using Mudflap is if security is a very big issue for your application. But even in this case GCC provides a better alternative against buffer overflow (see -fstack-protector[-all]).

like image 42
log0 Avatar answered Jan 19 '23 00:01

log0