Re: Why this code is working



jammie_linux@xxxxxxxxx wrote:
But when a function returns, the compiler reclaims all the memory
assigend to the local variables. By this theory, isn't it possible that
the memory where the string "This is local to the function"  was
stored, would also be reclaimed. In that case, the main's function str
will be pointing at a totally meaningless position.

No, because the string "this is local to the function" is *not* local to the function. String literals always have static duration, no matter where you declare them. The string literal continues to exist even after the function returns.


If you had instead used the string literal as an initialiser for a local array, then it would have returned an invalid pointer as you seem to expect.

Compare the following functions:

char *funct1()
{
  char *str = "This is a string literal with static duration.";
  return str;
}

char *funct2()
{
  char str[] = "But this one is used to initialise a local array.";
  return str;
}

The [] in funct2 make all the difference. Funct1 returns a valid pointer, but funct2 returns an invalid pointer.

--
Simon.
.



Relevant Pages

  • Re: ISAM error when trying to create tablelink
    ... Dim tDef As DAO.TableDef ... Doug Steele, Microsoft Access MVP ... Dim str As String ...
    (microsoft.public.access.modulesdaovba)
  • Re: Using the Dictionary object
    ... Private Sub LV_ItemCheck ... Dim Str As String ... MyNext = MyNext - 1 ...
    (microsoft.public.excel.programming)
  • Re: str() should convert ANY object to a string without EXCEPTIONS !
    ... For strings, ... 'ascii' codec can't encode character u'\ue863' in ... And it is correct to fail, ASCII is only defined within range, ... If that str() function has returned anything but error on this, ...
    (comp.lang.python)
  • Re: input a string in gcc
    ... Basically what my code is supposed to do is accept a string from user ... fgets (str, sizeof str, stdin); ... Think of pointers like of checks - if they aren't backed by ... i-th element of arr to point to the j-th char in str. ...
    (comp.lang.c)
  • Re: ISAM error when trying to create tablelink
    ... that will work to change an existing similar tabledef.connect string. ... Doug Steele, Microsoft Access MVP ... Dim rs As New ADODB.Recordset ... Dim str As String ...
    (microsoft.public.access.modulesdaovba)