Advertisement

Possibly simple question about C and strings

Started by March 15, 2000 07:11 PM
1 comment, last by Densun 24 years, 9 months ago
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."
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
Advertisement
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."

This topic is closed to new replies.

Advertisement