Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Can yo explain this...

Status
Not open for further replies.

nkm

Programmer
May 27, 2001
45
0
0
US
Hi

Is this code correct.

main()
{
char *p;

p = "This is what is assigned first";


printf("%s\n", p);

p = "This is second string";

printf("%s\n", p);

}

This piece of code works fine.
What I want to know is this acceptable??
Where are the literal strings allocated memory the stack/heap initialised memory etc... Can you give a memory map for this?

thanks

 
The code is ok.
Location of strings may be compiler/linker dependant, but const strings could go into a const data segment.
/JOlesen
 
What I think:
You should modify the string assignment by this way

strcpy(p,"This string was assign 1st"); etc.

because some Compilers make trouble on the direct assignment)


hnd
hasso55@yahoo.com

 
hi hnd,

using strcpy will lead to "Segmentation fault". Because no memory allocated for the character pointer "p".

As you said this direct assignment is compiler dependent only.

The literal strings are normally stored in the stack only. So the pointer "p" will point to that location. If you do any string manipulation with p, you will surely get the Segmentation fault.

Thanks
 
I Just saw in the moment that no Space is allocated. But that is a very dangerous Method and could lead to unpredicticable results especially with longer Strings and String operations..

I think the better way should be to allocate storage to the pointer. At least in the case of a fault the debugging will become easier.

hnd
hasso55@yahoo.com

 
hi ..

if you are using pointers {char *, int* - doesn't matter what} malloc your pointers *always*.

it is a good idea => more often that NOT you will segfault.

alternative is to just use static arrays

br: nagi

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top