Talk About Network

Google


Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > C++ > char table / po...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 1 of 8 Topic 45784 of 46738
Post > Topic >>

char table / pointer memory allocation

by mehafi@[EMAIL PROTECTED] May 6, 2008 at 11:59 AM

Hi,

Why this program work?

#include<iostream.h>
class test
{
public:
char *ptr;
void setPtr(char* p){
    ptr = p;
    }
void print(){
    cout << ptr << endl;
    }
};

main()
{
test t;
t.setPtr("abc");
t.print();
system("pause");
}

Is argument of function setPtr - "abc" - a tem****ary char table, made
on stack, which is deleted when setPtr function ends? If it is, the
pointer - ptr - point then to the memory addres which was deleted, so
print method should print random characters or may crash the program.
When I made char table using new:

main()
{
char* tab = new char[4];
strcpy(tab, "abc");
test t;
t.setPtr(tab);
delete[] tab;
t.print();
system("pause");
}

print() method prints random characters.
But why the first program doesn't crash / prints random chars ?

thanks in advance
best regards
mehafi
 




 8 Posts in Topic:
char table / pointer memory allocation
mehafi@[EMAIL PROTECTED]   2008-05-06 11:59:53 
Re: char table / pointer memory allocation
"sk_usenet" <  2008-05-06 12:23:33 
Re: char table / pointer memory allocation
mehafi@[EMAIL PROTECTED]   2008-05-06 21:19:18 
Re: char table / pointer memory allocation
Paavo Helde <nobody@[E  2008-05-07 14:47:31 
Re: char table / pointer memory allocation
James Kanze <james.kan  2008-05-09 02:37:17 
Re: char table / pointer memory allocation
Paavo Helde <nobody@[E  2008-05-12 01:58:33 
Re: char table / pointer memory allocation
James Kanze <james.kan  2008-05-12 03:06:08 
Re: char table / pointer memory allocation
Paavo Helde <nobody@[E  2008-05-12 17:14:33 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Tue Jul 8 23:58:01 CDT 2008.