On 12/28/06, Nico Heinze <[EMAIL PROTECTED]> wrote:

--- In [email protected], "mohansnayaka" <[EMAIL PROTECTED]> wrote:
>
> Hi all,
> We are using strcpy to copy strings in our app. This gave us
> problems when the destination buffer is not large enough.
> As a workaround, we wanted to replace calls to strcpy with
> strncpy. That is, replace calls to strcpy with say,
> my_strcpy(dest,src) which will internally find the
> destination buffer length.
>
> For this we need to know the destination buffer size. For
> statically allocated strings sizeof is returning the length
> of the array correctly, but not for malloced strings (char*).
> Hence we are not able to replace calls to strcpy with
> strncpy with appropriate length parameter.
>
> Is there any other way out? Changing all the static and dynamic
> allocations in the application is very very difficult (around 15k
> instances will have to be changed).

Mohan,

welcome to the real world of writing good and stable software.

No, there's no (safe, portable, and maintainable) way to tell how
large such blocks of dynamically allocated blocks are once they have
been allocated and you have thrown away the allocated size.

Yes, there is one way to tell the size of a dynamically allocated
memory structure:
Write your own allocation routines which keep track of the size of
every allocated block; then you can tell either the calling function
by some return parameter how large this memory block is, or you can
provide an auxiliary function which receives one pointer to memory
allocated by these routines and returns the allocated size.


The quickest way would probably write wrappers for malloc, realloc, and free
that allocate memory+sizeof(size_t), store the size in the first
sizeof(size_t) bytes, and return and take a pointer to base+sizeof(size_t)
bytes.

--
PJH

#713059 +(1255)- [X]

<SaintAlvus> Does the name Doctor Pavlov ring a bell?

Reply via email to