When memory is allocated during runtime it is easier to get the size of it by a function, rather than seeking in the code. Sometimes it can be hard to find the howmany value.
Printable View
When memory is allocated during runtime it is easier to get the size of it by a function, rather than seeking in the code. Sometimes it can be hard to find the howmany value.
What on earth are you talking about?
Why is it so hard to pass around the size value along with the pointer, which is so much more flexible since it allows you to use real arrays as well as dynamic memory (just look at fgets() for a prime example).
Assuming that your magic function could take care of the last two cases, the first two would be much harder to solve. Such a function would have to return an error status of some sort, then what are you supposed to do - bail out?Code:void foo ( char *ptr ) {
// There is NOTHING you can do here to tell whether ptr is
// a global variable, a local variable, or a malloc'ed variable
// or tell exactly how many bytes are being pointed at.
}
char global[10];
int main ( ) {
char local[20];
char *dynamic = malloc(30);
foo( global );
foo( local );
foo( dynamic );
foo( &dynamic[20] ); // is in dynamic memory, just not the start of it
}
If it really bugs you that much, create a struct which contains the pointer and the size, and pass that around instead. Or move to C++ and use the additional creature comforts offered by std::vector
I don't have any problem. But there should be a function to read the header generated by malloc() even if you can write programs without it easily, thats all.
Write and track your own. There is no need to pollute the language with more junk because people are too lazy or stupid to pay attention to what they're doing. They did enough of that already in C99.
Quzah.
I know what you say. But this is not like for example dynamic arrays. This is something that should being puted into language when it was created. I feel it should be standard in C an C++ but I don't insist on it.