An Array and memory problem

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Daniel Smith

    An Array and memory problem

    Hi,

    Two things confused me and I hope somebody can point out the wrong
    part, thanks in advance

    char * mytest ( const char src[])
    {
    char *ret;
    ret = new char;
    strncpy(ret, src, 5);
    return ret;
    }
    in main( ), I use:
    char *y = mytest("abcdef" );

    The code works but I think there are problems. I used 'new' to allocate
    some memory, how to release them?
    Another one:

    char * mytest ( const char src[])
    {
    char ret[10];
    strncpy(ret, src, 5);
    return ret;
    }
    in main ( ) : char *y = mytest("abcdef" );

    After we use 'char rec[10]', I think the it is in stack and 'rec' will
    be released after the function 'mytest' finishes. So I suppose I cannot
    get anything in 'y', but why did I get 'abcde' in y?

    Dan

  • Victor Bazarov

    #2
    Re: An Array and memory problem

    Daniel Smith wrote:
    Hi,
    >
    Two things confused me and I hope somebody can point out the wrong
    part, thanks in advance
    >
    char * mytest ( const char src[])
    {
    char *ret;
    ret = new char;
    You only allocate a _single_ char here. You need to check the length
    of the "string" passed to this function and allocate _one_more_ than
    the length:

    char *ret = new char[strlen(src) + 1]();
    strncpy(ret, src, 5);
    And here you copy _five_ of them, stomping all over the memory you
    don't even own. After that - undefined behaviour. You shouldn't be
    using 'strncpy' either. Just copy the whole thing using 'strcpy':

    strcpy(ret, src);
    return ret;
    }
    in main( ), I use:
    char *y = mytest("abcdef" );
    >
    The code works but I think there are problems. I used 'new' to
    allocate some memory, how to release them?
    Since the proper allocation is done using 'new[]', you need to do

    delete[] y;

    here.
    Another one:
    >
    char * mytest ( const char src[])
    {
    char ret[10];
    strncpy(ret, src, 5);
    return ret;
    Here you're returning a pointer to the local array. As soon as the
    function returns, the pointer is _invalid_.
    }
    in main ( ) : char *y = mytest("abcdef" );
    >
    After we use 'char rec[10]', I think the it is in stack and 'rec' will
    be released after the function 'mytest' finishes. So I suppose I
    cannot get anything in 'y', but why did I get 'abcde' in y?
    The behaviour is undefined. It could actually be (or pretend to be) what
    you had expected.

    V
    --
    Please remove capital 'A's when replying by e-mail
    I do not respond to top-posted replies, please don't ask


    Comment

    Working...