Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

Densun

Possibly simple question about C and strings

This topic is 6733 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

This has been bugging for awhile now. With C, you can declare a semi-string by making an array of characters. This can also be done with pointers, like so: char* string = "This is a string"; Does this allocate space like malloc () does? Can I delete it with free ()? Also, what about passing strings to functions (func ("string")). Does this allocate space that I should delete as well? --- Homer: "Hello. My name is Mr. Burns. I believe you have a letter for me." Post office: "Okay, Mr. Burns. What''s your first name?" Homer: "I don''t know."

Share this post


Link to post
Share on other sites
Advertisement
When you assign a pointer the value of a string, as such:

char* ptr = "yo!";

That string resides in the data segment. Basically, it''s not actually allocated, it''s loaded from disc when the executable is loaded and that''s that. You can change the value, but it''s not going to save back to disc.

As for the actual "ptr" variable. If you define it as a global variable, it is stored in the data segment just like the string. Otherwise, if you declare it as a local variable then it''s stored in the stack segment, and is trashed when the function returns.

It''s important to realize, though, that even if the "ptr" variable is trashed, the value it **USED** to hold is still good. That string is going nowhere until the programme exits.

I hope that helps.

-saxon

Share this post


Link to post
Share on other sites
No, this doesn''t allocate memory like malloc. When you declare a string like that in your program, you hardcode the size into the program. So if it''s 7 characters, it''ll never be more than 7 bytes unless you decide to overwrite some memory (very unpredictable). Malloc allocates free memory and gives you a pointer.

"When people tell you they want to hear the truth, you know that their lying."

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!