question about 'operator new'

Started by
4 comments, last by BASSOFeeSH 23 years, 10 months ago
here is the code:
    
int main()
{
     char *name = NULL;
     name = new char[11];

     cout << strlen(name);

     return 0;
}
     
The output of strlen is 15? I don't get it. Is this just because of random garbage in memory? "If at first you DO succeed...try not to look astonished!!" BASSOFeeSH@aol.com BASSOFeeSH ><> Edited by - Michael Tanczos on 6/5/00 11:10:18 PM
-- What would Sweetness do?
Advertisement
Yes, it's because of "random garbage". Since you are dynamically allocating the memory, there is no guarantee that the memory will be set to zero.

To get the desired result (0), you must set the first place of name to \0.

    int main(){char *name = NULL;name = new char[11];name[0] = '\0';cout << strlen(name);return 0;}    

There is usually no need to do this, since you will probably use string functions (such as strcpy() or gets()) that will make sure that the \0 is at the correct place, before you use the strlen() function.

/. Muzzafarath
Mad House Software

Edited by - Muzzafarath on June 6, 2000 12:26:51 PM
I'm reminded of the day my daughter came in, looked over my shoulder at some Perl 4 code, and said, "What is that, swearing?" - Larry Wall
Unrelated Q
How''d you guys put the code into that neat white background?
Need help? Well, go FAQ yourself. "Just don't look at the hole." -- Unspoken_Magi
It's easy Nazrix, put all code in [ source] code goes here [ /source] blocks (without the spaces in the tags).

                    int main(void){int i;for(i = 0; i < 5000; i++){printf("%d\n", i);}return 0;}        

I noticed that it doesn't color void when it's inside ()... Weird.

/. Muzzafarath
Mad House Software

Edited by - Muzzafarath on June 6, 2000 12:24:09 PM
I'm reminded of the day my daughter came in, looked over my shoulder at some Perl 4 code, and said, "What is that, swearing?" - Larry Wall
                    #include <stdio.h>                    int main ( void ){puts("Hey that's cool! Thanks.");}                            



PS Muzzafarath, if you put void with spaces around it, it is blue...just figured that out


Edited by - Nazrix on June 6, 2000 1:50:30 PM
Need help? Well, go FAQ yourself. "Just don't look at the hole." -- Unspoken_Magi
    int Sprite::DistanceTo( Sprite *s ){	return (int)Distance(x,y,s->x,s->y);}    


Cool...


lntakitopi@aol.com | http://geocities.com/guanajam/

This topic is closed to new replies.

Advertisement