C string functions

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • gc260262@belgacom.net

    C string functions

    Hi,

    I need functions that would return null terminated strings for me, for
    example:

    char *HTMLi(const char *string)

    This function receives a pointer to a null terminated string, and
    should return <i>This was the string</i>.

    To make it more complex, I could even return the result of the above
    function to this:

    char *HTMLb(const char *string)

    As a result, this is what I expect to have <b><i>This was the
    string</i></b>

    How about allocating memory; I assume if I allocate memory in these
    functions, and never free it, this is a so called memory leak.

    Does somebody has a sample code for me having the same logic? Your
    feedback is really appreciated!


    Thanks,

  • Emmanuel Delahaye

    #2
    Re: C string functions

    gc260262@belgac om.net wrote on 01/06/05 :[color=blue]
    > Hi,
    >
    > I need functions that would return null terminated strings for me, for
    > example:
    >
    > char *HTMLi(const char *string)
    >
    > This function receives a pointer to a null terminated string, and
    > should return <i>This was the string</i>.
    >
    > To make it more complex, I could even return the result of the above
    > function to this:
    >
    > char *HTMLb(const char *string)
    >
    > As a result, this is what I expect to have <b><i>This was the
    > string</i></b>
    >
    > How about allocating memory; I assume if I allocate memory in these
    > functions, and never free it, this is a so called memory leak.
    >
    > Does somebody has a sample code for me having the same logic? Your
    > feedback is really appreciated!
    >
    > Thanks,[/color]

    The obvious way : the function returns an allocated bloc that you have
    to free after use.

    Another solution could fit.

    define a size:

    size_t size = 128;
    define a string
    char *s = malloc(size + 1);

    Maintain the size and allocated memory through the converter functions
    :

    s = HTMLi (s, &size, "Hello world");
    printf ("%s", s);
    fflush (stdout);

    s = HTMLb (s, &size, s);
    printf ("%s", s);
    fflush (stdout);

    Use memmove() to make the copies and realloc() on request (and update
    size accordingly). On realloc() error, just exit(), or free() and
    return NULL, but the application would have to check against NULL each
    time... (can be done simply with some embedded goto...)

    #define CHK\
    do {if (s==NULL) goto err;} while (0)


    s = HTMLi (s, &size, "Hello world");
    CHK;
    printf ("%s", s);
    fflush (stdout);

    s = HTMLb (s, &size, s);
    CHK;
    printf ("%s", s);
    fflush (stdout);

    err:

    Once finished, just free the allocated bloc.

    --
    Emmanuel
    The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
    The C-library: http://www.dinkumware.com/refxc.html

    "Mal nommer les choses c'est ajouter du malheur au
    monde." -- Albert Camus.

    Comment

    • Paul Mesken

      #3
      Re: C string functions

      On 1 Jun 2005 12:31:42 -0700, gc260262@belgac om.net wrote:
      [color=blue]
      >Does somebody has a sample code for me having the same logic? Your
      >feedback is really appreciated![/color]

      There are several ways to do it in C but I'd like to point out that C
      is not exactly a language of choice for string operations (always been
      a bit of a weak point of C) so, perhaps, you should consider another
      programming language for your application if it contains lots of
      string handling (Perl, for example).

      Comment

      • gc260262@belgacom.net

        #4
        Re: C string functions

        Salut Emmanuel!

        Thank you for your clear explanation!

        I have only one question; if I need to do a realloc in a function,
        won't this cost a lot in performance?


        Regards
        Dirk

        Comment

        • Michael Mair

          #5
          Re: C string functions

          gc260262@belgac om.net wrote:[color=blue]
          > Salut Emmanuel!
          >
          > Thank you for your clear explanation!
          >
          > I have only one question; if I need to do a realloc in a function,
          > won't this cost a lot in performance?[/color]

          Please quote enough context so that everyone can see what
          you are responding to -- the original message may for example
          not have made it to some newsserver (yet).

          As for performance issues: The C standard does not tell us
          anything about relative performance.
          A good rule of thumb for many, but not all systems and
          implementations is to start out with a sensible buffer size which
          makes realloc()ating a rare event; on realloc()ation, rather
          increase the buffer size by a certain factor (1.5 or 2, for example)
          than by a fixed amount in order to keep the number of times low.

          BTW: It is possible that your implementation gives you a larger
          chunk of memory than you requested, to the effect that at reallocation
          only administrative information has to be updated.

          If you implement a solution using realloc() which is too slow,
          be sure to measure carefully to find out where the time loss
          happens, i.e. whether this is really the fault of realloc().

          Cheers
          Michael
          --
          E-Mail: Mine is an /at/ gmx /dot/ de address.

          Comment

          • indiangeek@gmail.com

            #6
            Re: C string functions

            gc260262@belgac om.net wrote:
            [color=blue]
            > Salut Emmanuel!
            >
            > Thank you for your clear explanation!
            >
            > I have only one question; if I need to do a realloc in a function,
            > won't this cost a lot in performance?
            >
            >
            > Regards
            > Dirk[/color]

            Hi Dirk,
            The problem is, your destination string is larger then your source string.
            So, you need to realloc/malloc if you want to maintain the prototype you
            specified. However, you can take the approach to make the situation a
            little better where you allocate the maximum chunk of memory to build the
            full HTML upfront. Then, use the following function to modify it in-place.

            I have modified the prototype a little and you don't need to define HTMLi
            HTMLb indipendently. For example the following program...

            #include<stdio. h>
            #include<stdlib .h>
            #include<string .h>

            #define BOLD "b"
            #define ITALICS "i"

            int HTMLx(char *str,int max_size, char *type)
            {
            int prefix_len;
            int orig_len;

            prefix_len = strlen(type) + 2;
            orig_len = strlen(str);
            if (max_size < (prefix_len+1)* 2)
            return -1; /* Failure... not enough space */

            memmove(str+pre fix_len,str,ori g_len+1);

            /* Build the prefix */
            str[0]='<';
            memcpy(str+1,ty pe,strlen(type) );
            str[prefix_len - 1]='>';

            /* Build the suffix */
            str[prefix_len + orig_len] = '<';
            str[prefix_len + orig_len + 1] = '/';
            memcpy(str+pref ix_len+orig_len +2,type,strlen( type));
            str[prefix_len + orig_len + strlen(type) + 2] = '>';
            }

            int main()
            {
            char *str = malloc(1000);
            sprintf(str,"He llo Worldie");
            HTMLx(str,1000, ITALICS);
            printf("%s\n",s tr);
            HTMLx(str,1000, BOLD);
            printf("%s\n",s tr);
            return 0;
            }



            Will give you output of :

            <i>Hello Worldie</i>
            <b><i>Hello Worldie</i></b>

            Also, you can make it more robust where, when you run out of memory, it
            reallocs another chunk. That will improve performance in terms of using
            reduced number of reallocs.

            Hope that helps.
            - IG

            Comment

            • Malcolm

              #7
              Re: C string functions


              <gc260262@belga com.net> wrote[color=blue]
              >
              > I have only one question; if I need to do a realloc in a function,
              > won't this cost a lot in performance?
              >[/color]
              Yes.
              calls to malloc() or realloc() are always expensive in C terms, though not
              always in terms of other languages. Precise execution times do of course
              vary from platform to platform.

              A good method is to call malloc() for as much memory as you will ever
              realistically need, keeping realloc() in reserve so that formally the
              function is unbounded. Then call realloc() once at the end to shrink the
              block to the required size.


              Comment

              • Emmanuel Delahaye

                #8
                Re: C string functions

                indiangeek@gmai l.com wrote on 02/06/05 :[color=blue]
                > int main()
                > {
                > char *str = malloc(1000);
                > sprintf(str,"He llo Worldie");
                > HTMLx(str,1000, ITALICS);
                > printf("%s\n",s tr);
                > HTMLx(str,1000, BOLD);
                > printf("%s\n",s tr);
                > return 0;
                > }[/color]

                You forgot to free() the block after use and to check against NULL...

                --
                Emmanuel
                The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
                The C-library: http://www.dinkumware.com/refxc.html

                "Mal nommer les choses c'est ajouter du malheur au
                monde." -- Albert Camus.

                Comment

                • CBFalconer

                  #9
                  Re: C string functions

                  gc260262@belgac om.net wrote:[color=blue]
                  >
                  > I need functions that would return null terminated strings for me, for
                  > example:
                  >
                  > char *HTMLi(const char *string)
                  >
                  > This function receives a pointer to a null terminated string, and
                  > should return <i>This was the string</i>.[/color]

                  I suggest you build your code around strlcpy and strlcat. Source,
                  documentation, and references are available at:

                  <http://cbfalconer.home .att.net/download/strlcpy.zip>

                  --
                  "I conclude that there are two ways of constructing a software
                  design: One way is to make it so simple that there are obviously
                  no deficiencies and the other way is to make it so complicated
                  that there are no obvious deficiencies." -- C. A. R. Hoare


                  Comment

                  • Michael Knaup

                    #10
                    Re: C string functions

                    gc260262@belgac om.net wrote:
                    [color=blue]
                    > Hi,
                    >
                    > I need functions that would return null terminated strings for me, for
                    > example:
                    >
                    > char *HTMLi(const char *string)
                    >
                    > This function receives a pointer to a null terminated string, and
                    > should return <i>This was the string</i>.
                    >
                    > To make it more complex, I could even return the result of the above
                    > function to this:
                    >
                    > char *HTMLb(const char *string)
                    >
                    > As a result, this is what I expect to have <b><i>This was the
                    > string</i></b>
                    >
                    > How about allocating memory; I assume if I allocate memory in these
                    > functions, and never free it, this is a so called memory leak.
                    >
                    > Does somebody has a sample code for me having the same logic? Your
                    > feedback is really appreciated!
                    >
                    >
                    > Thanks,[/color]

                    Working directly with strings is not a good idea for your problem i think.
                    Maybe you shhould use a stack of strings. Were each element has two strings
                    (the opening tag and the closing tag or NULL). All you have to do then is
                    pushing your data onto the stack, print the stack or convert it to a flat
                    string and freeing the stack.


                    --
                    Michael Knaup

                    Comment

                    • indiangeek@gmail.com

                      #11
                      Re: C string functions

                      Emmanuel Delahaye wrote:
                      [color=blue]
                      > indiangeek@gmai l.com wrote on 02/06/05 :[color=green]
                      >> int main()
                      >> {
                      >> char *str = malloc(1000);
                      >> sprintf(str,"He llo Worldie");
                      >> HTMLx(str,1000, ITALICS);
                      >> printf("%s\n",s tr);
                      >> HTMLx(str,1000, BOLD);
                      >> printf("%s\n",s tr);
                      >> return 0;
                      >> }[/color]
                      >
                      > You forgot to free() the block after use and to check against NULL...
                      >[/color]

                      :-).
                      Yes, I just skipped the error checks. It was just a prototype of what could
                      be done.
                      Ideally, along with those checks, we should be checking error code of HTMLx
                      also to see if it worked.

                      --
                      -IG

                      Comment

                      • Kevin Handy

                        #12
                        Re: C string functions

                        gc260262@belgac om.net wrote:[color=blue]
                        > Hi,
                        >
                        > I need functions that would return null terminated strings for me, for
                        > example:
                        >
                        > char *HTMLi(const char *string)[/color]

                        As per your description:

                        char *HTMLi(const char *string)
                        {
                        return "<i>This was the string</i>";
                        }
                        [color=blue]
                        >
                        > This function receives a pointer to a null terminated string, and
                        > should return <i>This was the string</i>.
                        >
                        > To make it more complex, I could even return the result of the above
                        > function to this:
                        >
                        > char *HTMLb(const char *string)
                        >[/color]
                        And just as easily

                        char *HTMLb(const char *string)
                        {
                        return "<b><i>This was the string</i></b>";
                        }

                        [color=blue]
                        > As a result, this is what I expect to have <b><i>This was the
                        > string</i></b>
                        >
                        > How about allocating memory; I assume if I allocate memory in these
                        > functions, and never free it, this is a so called memory leak.
                        >
                        > Does somebody has a sample code for me having the same logic? Your
                        > feedback is really appreciated![/color]

                        ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
                        http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
                        ----= East and West-Coast Server Farms - Total Privacy via Encryption =----

                        Comment

                        • Gregory Pietsch

                          #13
                          Re: C string functions



                          gc260262@belgac om.net wrote:[color=blue]
                          > Hi,
                          >
                          > I need functions that would return null terminated strings for me, for
                          > example:
                          >
                          > char *HTMLi(const char *string)
                          >
                          > This function receives a pointer to a null terminated string, and
                          > should return <i>This was the string</i>.
                          >
                          > To make it more complex, I could even return the result of the above
                          > function to this:
                          >
                          > char *HTMLb(const char *string)
                          >
                          > As a result, this is what I expect to have <b><i>This was the
                          > string</i></b>
                          >
                          > How about allocating memory; I assume if I allocate memory in these
                          > functions, and never free it, this is a so called memory leak.
                          >
                          > Does somebody has a sample code for me having the same logic? Your
                          > feedback is really appreciated!
                          >
                          >
                          > Thanks,[/color]

                          This is yet another question with the same answer. Get FreeDOS Edlin
                          2.5 (available on ibiblio or alt.sources) and dyke out the
                          string-handling code.

                          Then, you could do something like:

                          STRING_T *HTMLi(STRING_T *this)
                          {
                          DSinsertcstr(th is, 0, "<i>", NPOS);
                          DSappendcstr(th is, "</i>", NPOS);
                          return this;
                          }

                          /* Gregory Pietsch */

                          Comment

                          Working...