473,657 Members | 2,493 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

[Noob]String memory allocation

DJP
Hi,

I had sort of a noob question on memory allocation for strings.

char *str1 = "Hello World!";
char str2[] = "Hello World!";

In the above bit are both str1 & str2 stack allocated or heap allocated
or otherwise? Also, unless explicitly malloc'ing a string buffer are we
not required to free it? Or are there other circumstances in which we
are required to free?

Hope to hear from someone out there.

Thanks.

DJP

Nov 15 '06 #1
7 1922
2006-11-15 <11************ *********@m7g20 00cwm.googlegro ups.com>,
DJP wrote:
Hi,

I had sort of a noob question on memory allocation for strings.

char *str1 = "Hello World!";
char str2[] = "Hello World!";

In the above bit are both str1 & str2 stack allocated or heap allocated
or otherwise?
Well - the off-topic answer is, it depends on whether this is inside
a function or not. They will never be "heap allocated" in the sense you
find on typical implementations , only malloc (and functions that call
malloc, some of which can be surprising) does that.

(mostly back to on-topic) In either case, the first one is in a static
nonwritable area of storage. Outside a function, the latter is in static
writable storage, but inside a function, it is in "automatic" storage
(that is, what you might call the stack)
Also, unless explicitly malloc'ing a string buffer are we
not required to free it? Or are there other circumstances in which we
are required to free?
You are never required to, nor permitted to, free() or realloc()
any pointer whose value did not originate from a malloc(), calloc(), or
realloc() call that you yourself made. [OT] or certain non-standard
functions which are documented to call malloc [/OT]
Hope to hear from someone out there.
Nov 15 '06 #2
DJP wrote:
Hi,

I had sort of a noob question on memory allocation for strings.

char *str1 = "Hello World!";
char str2[] = "Hello World!";

In the above bit are both str1 & str2 stack allocated or heap
allocated or otherwise?
These are not portable terms. The only really important thing is
storage duration. Where things are stored is implementation specific.

In the first case, the address of the first character of an anonymous
array is stored in a pointer. That array itself has static storage
duration, which means that it is around for the entire program. It is
undefined behavior to modify a string literal, and it would be better
to make str1 a const pointer.

The second form depends on how it's declared. If it is outside of any
function, or is declared with the "static" keyword, then it will also
have static storage duration. Otherwise, it has automatic, which means
it ceases to exist when the program leaves the enclosing scope.
Also, unless explicitly malloc'ing a string
buffer are we not required to free it?
Not usually.
Or are there other
circumstances in which we are required to free?
Unless it's a libary function that returns allocated memory.
Hope to hear from someone out there.


Brian
Nov 15 '06 #3
DJP
(mostly back to on-topic) In either case, the first one is in a static
nonwritable area of storage. Outside a function, the latter is in static
writable storage, but inside a function, it is in "automatic" storage
(that is, what you might call the stack)
Thanks for your response. Also, can you elaborate a little bit about
the "static nonwritable area of storage" and the "static writable
storage" that you mention? Thanks.

Nov 15 '06 #4
2006-11-15 <11************ **********@i42g 2000cwa.googleg roups.com>,
DJP wrote:
>(mostly back to on-topic) In either case, the first one is in a static
nonwritable area of storage. Outside a function, the latter is in static
writable storage, but inside a function, it is in "automatic" storage
(that is, what you might call the stack)

Thanks for your response. Also, can you elaborate a little bit about
the "static nonwritable area of storage" and the "static writable
storage" that you mention? Thanks.
It means that it doesn't go away until you exit the program and you
cannot*, or, for writable, can, write to it. [OT] On some systems, these will
be loaded into memory from disk when the program is started in different
'segments' or 'sections', and the nonwritable areas will be marked as
such in the memory protection [/OT]

*Note that your implementation won't necessarily stop you from trying.
Instead, bad things might happen later on at an unrelated point in the
program, or when you try to port it to another system.
Nov 15 '06 #5
Default User wrote:
DJP wrote:
>Also, unless explicitly malloc'ing a string
buffer are we not required to free it?

Not usually.
>Or are there other
circumstance s in which we are required to free?

Unless it's a libary function that returns allocated memory.
The only standard library functions that return allocated memory are
malloc, calloc and realloc.

Any other C function in a library may of course return a pointer that
must be freed[1], but that pointer must have been returned by a malloc,
calloc or realloc call within the library[2].

[1] Or a pointer to somewhere within a memory block that must be freed.
It may not be a pointer to the first byte of that memory block.

[2] Or within another library or other code that is linked into the
final program.

--
Simon.
Nov 15 '06 #6
Simon Biber wrote:
Default User wrote:
DJP wrote:
Also, unless explicitly malloc'ing a string
buffer are we not required to free it?
Not usually.
Or are there other
circumstances in which we are required to free?
Unless it's a libary function that returns allocated memory.

The only standard library functions that return allocated memory are
malloc, calloc and realloc.
I don't see the word the word "standard" in my sentence above.
Any other C function in a library may of course return a pointer that
must be freed[1], but that pointer must have been returned by a
malloc, calloc or realloc call within the library[2].
True, but as library routines are often opaque to the user, a new user
won't necessarily know that. From their point of view, some library
routine *cough* strdup() *cough* could return allocated memory, they
will need to check.

Brian
Nov 15 '06 #7
DJP wrote:
(mostly back to on-topic) In either case, the first one is in a
static nonwritable area of storage. Outside a function, the latter
is in static writable storage, but inside a function, it is in
"automatic" storage (that is, what you might call the stack)

Thanks for your response. Also, can you elaborate a little bit about
the "static nonwritable area of storage" and the "static writable
storage" that you mention? Thanks.
Besides the information you received elsewhere, you may want to review
the FAQ on the subject:
<http://c-faq.com/decl/strlitinit.html >
In fact, reviewing all the string, array, and pointer entries would be
a good idea.

Brian
Nov 15 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
8196
by: Olumide | last post by:
In the following C++ class, MyClass{ // Members } From which I create two objects (using the default constructor), (1) MyClass *object1 = new MyClass(); // Stack (2) MyClass object2 = MyClass(); // Stack or Heap?
8
2140
by: Ivan Shevanski | last post by:
Alright heres another noob question for everyone. Alright, say I have a menu like this. print "1. . .Start" print "2. . .End" choice1 = raw_input("> ") and then I had this to determine what option.
2
1237
by: Donald | last post by:
I am trying print the length of a managed array, but I cannot figure out how to correctly cast the result so String::Format will use it. I wrote a simple test to duplicate the problem (below) -- can anybody explain to me why the following generates an error? int ai __gc = new int __gc; Console::WriteLine(ai->Length); Console::WriteLine(String::Format(S"Length of ai is {0}", __box(ai->Length))); The first Writeline returns the correct...
9
5024
by: pointer noob | last post by:
Hi, I am trying to write a bit of code to iterate through memory addresses and if the address is divisable by 2 then write one byte, if not write a different byte. I am having trouble with the pointer to the address incremented by for loop. unsigned long i; for(i=0xB8000; i<0xC0000; i++)
10
1720
by: stylecomputers | last post by:
Hey guys, I am absolutely new to Linux programming, with no w######s programming experience except a small amount of C++ console apps. Reasonably new to Linux, BSD etc, got good sound networking base of knowledge and dont have any problem working the command line etc. I want to learn a language that I can use in my networking duties that is most likely to be of use to me. I have a few choices I can think of being:
2
6290
by: jaime_v | last post by:
This is for all those STL-heads out there, this mught be trivial for you but I am a noob with the STL. I am having to implement a system in which I wil have many (thousands) of containers, I have been noticing that once you delete an element from a list memory is not released until program termination. for the sake of argument lets say that the code looks like: #include <iostream> #include <list> using namespace std; int main(int...
4
1212
by: jobs | last post by:
Three noob questions. Please help. 1. Is there a way to have arguments on subroutine that are optional? 2. Say I need to convert datetime to string..in this format : 2006-09-07 23:00:00.000
12
4141
by: Simon | last post by:
Hi all, I'm having a baffling problem with a windows service that I'm working on. Basically, I am using a typed dataset to insert a large number of rows into an SQL Server 2005 database. But there's a memory leak that seems to be to do with calling the data adapters update method. It's making the memory usage go through the roof and ultimately the service crashes after running out of memory.
11
3559
by: Bryan Parkoff | last post by:
I want to know how much static memory is limited before execution program starts. I would write a large array. The large array has 65,536 elements. The data size is double word. The static memory would allocate 256K. The 256K is a fixed memory size. After the compiler has completed compiling header and source code, the execution program might fail to run or crash. The operating system might do not display error message saying,...
0
8421
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8844
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8742
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7354
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6177
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5643
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2743
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.