Would this be safe?

From: Materialised (Materialised_at_privacy.net)
Date: 03/29/05


Date: Tue, 29 Mar 2005 21:20:26 +0100

I am new to the C++ world, after spending many years as a C programmer.
I am attempting to convert a std::string to a array of characters (C
string), to enable me to send the data via a socket.
I realise that discussion of none standard functions is off topic here,
so for the purpose of this discussion, lets pretend that is not what I
am trying to achieve.

Coming from a C background, I have had it drilled into me to always try
to avoid buffer overflows especially when dealing with arrays of
characters. So with this in mind I ask the following question:

Is the code below safe?

#include <iostream>
#include <cstdio>
#include <string>

int main (void)
{
        std::string hello, hello2;
        hello = "This is a C++ String";

        std::cout << hello << std::endl;
        const char *cstring = hello.c_str();
        for(int i = 0; i < strlen(cstring); i++){
                if( i == 7)
                        printf(" \nn\no\nt\n");
                printf("%c\n", cstring[i]);
        }

        hello2 = cstring;
        std::cout << hello2 << std::endl;
        
        return 0;
}

Thanks in advance.

-- 
Materialised
perl -e 'printf %silto%c%sal%c%s%ccodegurus%corg%c, ma, 58, mw, 107, 
'er',  64, 46, 10;'
Homer: "All right, let's not panic. I'll make the money by selling one 
of my livers. I can get by with one"


Relevant Pages

  • Re: sending echo to all clients
    ... I did initialize it up properly, ... There is only one array and that is an array of pollfd structures named ... as an array of characters only but then I can't because sendsends bytes ... you receive C-style strings, so there's really no point to doing it. ...
    (comp.unix.programmer)
  • Re: Subquery Confusion
    ... Then I got this crazy idea that an Array can only contain a maximum ... number of characters, ... Then I decide that maybe I'm completely wrong with my query, ... it out of Excel VBA and spit it into Microsoft SQL Server Management ...
    (microsoft.public.excel.programming)
  • Re: ifstream::get() surprise
    ... Extracts characters and stores them into successive locations ... > null character into the next successive location of the array. ... since the rule is to post the shortest code suffering from the ...
    (comp.lang.cpp)
  • Re: Problem with inserting bytea into postgresql
    ... > This byte array is serialized object. ... > ByteArrayOutputStream outputStream = new ByteArrayOutputStream; ... and the characters are encoded via UTF-8. ...
    (comp.lang.java.help)
  • Re: what does strod return??
    ... This is not a large enough array to hold four digits of input. ... Using the scanf "%s" conversion specifier without a length parameter ... scanfwill attempt to pull characters from ... there is undefined behavior and there ...
    (comp.lang.c)