473,804 Members | 2,124 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C beginer

I am trying out a few things, need ur help to clear a doubt:
I have a character pointer initialised as below:
char *ptr = "TestString ";
When i print this ptr thru printf , it prints the string properly.
But when i delete this ptr using delete ptr, it throws assertion.
following are my questions:
1) When i do char *ptr = "TestString "; does it allocate sufficient
memory?
2) How did the printf accessed the value properly? did the above
assignment copy the values in heap?

Thanks for any light thrown into this.

Nov 15 '05 #1
11 2086
Le 08-11-2005, CBegin <st********@gma il.com> a écrit*:
I am trying out a few things, need ur help to clear a doubt:
I have a character pointer initialised as below:
char *ptr = "TestString ";
ptr is a pointer that point on the automatic read-only
char array "TestString ".
When i print this ptr thru printf , it prints the string properly.
But when i delete this ptr using delete ptr, it throws assertion.
Notice that delete is a C++ keyword, not C one.
But the error would be quite the same with free.
following are my questions:
1) When i do char *ptr = "TestString "; does it allocate sufficient
memory?
Yes. But allocation is done in the memory of automatic variables,
and free must be called only on dynamic memory (obtained with
malloc, calloc, realloc).
2) How did the printf accessed the value properly? did the above
assignment copy the values in heap?


printf get a pointer on the array "TestString ". So, it could
access it. The array is not copied.

Marc Boyer
Nov 15 '05 #2

Marc Boyer wrote:
Le 08-11-2005, CBegin <st********@gma il.com> a écrit :
I am trying out a few things, need ur help to clear a doubt:
I have a character pointer initialised as below:
char *ptr = "TestString ";
ptr is a pointer that point on the automatic read-only
char array "TestString ".

Thanks a lot,

Is this whats happening internally:
char *ptr = "TestString ";
gets expanded to:
const char temp[] = "TestString ";
ptr = temp; // ptr holds the address of read only buffer
//
so when i try free p, it actually tries to clean the memory assigned to
temp variable, which is not stored in heap, but on stack.

Am i correct?
When i print this ptr thru printf , it prints the string properly.
But when i delete this ptr using delete ptr, it throws assertion.


Notice that delete is a C++ keyword, not C one.
But the error would be quite the same with free.
following are my questions:
1) When i do char *ptr = "TestString "; does it allocate sufficient
memory?


Yes. But allocation is done in the memory of automatic variables,
and free must be called only on dynamic memory (obtained with
malloc, calloc, realloc).
2) How did the printf accessed the value properly? did the above
assignment copy the values in heap?


printf get a pointer on the array "TestString ". So, it could
access it. The array is not copied.

Marc Boyer


Nov 15 '05 #3
Le 08-11-2005, CBegin <st********@gma il.com> a écrit*:
Marc Boyer wrote:
Le 08-11-2005, CBegin <st********@gma il.com> a écrit :
> I am trying out a few things, need ur help to clear a doubt:
> I have a character pointer initialised as below:
> char *ptr = "TestString ";
ptr is a pointer that point on the automatic read-only
char array "TestString ".

Thanks a lot,

Is this whats happening internally:
char *ptr = "TestString ";
gets expanded to:
const char temp[] = "TestString ";
ptr = temp; // ptr holds the address of read only buffer


You are right (except perhaps the 'const': this is the right
idea, but I am not sure this is exactly the same, this is
why I have use 'read-only' instead of 'const').
//
so when i try free p, it actually tries to clean the memory assigned to
temp variable, which is not stored in heap, but on stack.

Am i correct?


Yes, except that, to my knowledge, there is no stack in the C standart.
But, there is one in a lot of implementations .

Marc Boyer
Nov 15 '05 #4
"CBegin" <st********@gma il.com> wrote:
Marc Boyer wrote:
Le 08-11-2005, CBegin <st********@gma il.com> a =E9crit :
I am trying out a few things, need ur help to clear a doubt:
I have a character pointer initialised as below:
char *ptr = "TestString ";
ptr is a pointer that point on the automatic read-only
char array "TestString ".

Thanks a lot,

Is this whats happening internally:
char *ptr = "TestString ";
gets expanded to:
const char temp[] = "TestString ";
ptr = temp; // ptr holds the address of read only buffer
//
so when i try free p, it actually tries to clean the memory assigned to
temp variable,


Almost. String literals have static duration (i.e., they do not get
deallocated when you leave the block where you "define" them (scare
quotes around "define" because it's clearly not a real definition as,
ahem, defined in the C Standard, but the thing comes into existence
nevertheless and you asked for it to exist)); and string literals are
not modifiable, but (for reasons of convenience) not acutally const; so
the definition of temp should actually be

static char temp[] = "TestString ";

but you still can't write to it.
Apart from that, yes, that's more or less what happens behind the
scenes.
which is not stored in heap, but on stack.


No. First, there is no guarantee that allocated objects are stored in a
structure called (or even necessarily describable as) "the heap"; and
there is no guarantee that the area in which automatic objects are
stored is called "the stack", although it _is_ very unlikely not to be
arranged as one.
Second, as I wrote above, string literals have static duration. This is
a third category, separate from objects with allocated duration ("the
heap") and objects with automatic duration ("the stack"). It is often
called something like "global memory".

Basically, allocated memory (memory you get from malloc() and friends)
exists from the point at which you ask for it, until the point you
free() it (or, AFAIK, in C++, delete it). Automatic memory, which is all
normal objects defined within a function, exists from the start of the
block it is declared in until the end of that block. Static memory,
which is all objects declared outside a function as well as all objects
declared static, _and_ your string literal, exists as long as the
program runs.
(C99 adds some subtleties to this, involving things like compound
literals and variable length arrays, but you need not concern yourself
with these - yet.)

The effect on your program, though, is the same. You cannot free()
static memory any more than you can free() automatic memory. You can
only call free() on memory you have received from malloc(), calloc() or
realloc(), and even then only on the base pointer of the block, not on
any pointer inside it; and only once per memory block.

Richard
Nov 15 '05 #5
Le 08-11-2005, CBegin <st********@gma il.com> a écrit*:
I am trying out a few things, need ur help to clear a doubt:
I have a character pointer initialised as below:
char *ptr = "TestString ";


ptr is a pointer that point on the automatic read-only
char array "TestString ".


Are you sure? I thought that the "TestString " value will be put in
static storage even though the static keyword is omitted, so that it will
remain as long as the program is running.

char ptr[]= "TestString " is automatic, I believe.

The reason free() failes, is because the memory pointer received by free
is not a valid for freeing on the heap ?

Best Regards
Steffen
Nov 15 '05 #6
Le 08-11-2005, Steffen Fiksdal <st******@ulrik .uio.no> a écrit*:
This message is in MIME format. The first part should be readable text,
while the remaining parts are likely unreadable without MIME-aware tools.

---259979764-50747693-1131441565=:298 07
Content-Type: TEXT/PLAIN; charset=iso-8859-1; format=flowed
Content-Transfer-Encoding: 8BIT

Le 08-11-2005, CBegin <st********@gma il.com> a écrit*:
I am trying out a few things, need ur help to clear a doubt:
I have a character pointer initialised as below:
char *ptr = "TestString ";
ptr is a pointer that point on the automatic read-only
char array "TestString ".


Are you sure? I thought that the "TestString " value will be put in
static storage even though the static keyword is omitted, so that it will
remain as long as the program is running.


Yes, but I was trying to give not too much details. But you are
right.
char ptr[]= "TestString " is automatic, I believe.
Yes, and is not read-ondly.
The reason free() failes, is because the memory pointer received by free
is not a valid for freeing on the heap ?


To be really accurate, there is no "heap" in C. free must
called on a pointer obtained with malloc/calloc/realloc (and
perhaps some others...)

Marc Boyer
Nov 15 '05 #7

Richard Bos wrote:
"CBegin" <st********@gma il.com> wrote:
Marc Boyer wrote:
Le 08-11-2005, CBegin <st********@gma il.com> a =E9crit :
> I am trying out a few things, need ur help to clear a doubt:
> I have a character pointer initialised as below:
> char *ptr = "TestString ";

ptr is a pointer that point on the automatic read-only
char array "TestString ". Thanks a lot,

Is this whats happening internally:
char *ptr = "TestString ";
gets expanded to:
const char temp[] = "TestString ";
ptr = temp; // ptr holds the address of read only buffer
//
so when i try free p, it actually tries to clean the memory assigned to
temp variable,


Almost. String literals have static duration (i.e., they do not get
deallocated when you leave the block where you "define" them (scare
quotes around "define" because it's clearly not a real definition as,
ahem, defined in the C Standard, but the thing comes into existence
nevertheless and you asked for it to exist)); and string literals are
not modifiable, but (for reasons of convenience) not acutally const; so
the definition of temp should actually be

static char temp[] = "TestString ";

but you still can't write to it.
Apart from that, yes, that's more or less what happens behind the
scenes.
which is not stored in heap, but on stack.


No. First, there is no guarantee that allocated objects are stored in a
structure called (or even necessarily describable as) "the heap"; and
there is no guarantee that the area in which automatic objects are
stored is called "the stack", although it _is_ very unlikely not to be
arranged as one.

Much clear now.
again coming back to this declaration:
char* p = "TestString "; //
p does point to some location where this temp static var is stored.
I am using MSDEV IDE, there in the memory view, i can see that p points
to
a location which contains text specified. (This was also evident from
the printf statement, which executed properly).
But When I do *(p+1) = 'M'; It should be replacing the existing text in
address pointed by p+1 -> location of character 'e' . but it again
gives an exception. If it was a read only buffer it should have given a
compile time error. Would like to understand more on this temp
variables usage.....

Second, as I wrote above, string literals have static duration. This is
a third category, separate from objects with allocated duration ("the
heap") and objects with automatic duration ("the stack"). It is often
called something like "global memory".

Basically, allocated memory (memory you get from malloc() and friends)
exists from the point at which you ask for it, until the point you
free() it (or, AFAIK, in C++, delete it). Automatic memory, which is all
normal objects defined within a function, exists from the start of the
block it is declared in until the end of that block. Static memory,
which is all objects declared outside a function as well as all objects
declared static, _and_ your string literal, exists as long as the
program runs.
(C99 adds some subtleties to this, involving things like compound
literals and variable length arrays, but you need not concern yourself
with these - yet.)

The effect on your program, though, is the same. You cannot free()
static memory any more than you can free() automatic memory. You can
only call free() on memory you have received from malloc(), calloc() or
realloc(), and even then only on the base pointer of the block, not on
any pointer inside it; and only once per memory block.

Richard


Nov 15 '05 #8
Le 08-11-2005, CBegin <st********@gma il.com> a écrit*:
Richard Bos wrote:
"CBegin" <st********@gma il.com> wrote:
> Marc Boyer wrote:

arranged as one.

Much clear now.
again coming back to this declaration:
char* p = "TestString "; //
p does point to some location where this temp static var is stored.
I am using MSDEV IDE, there in the memory view, i can see that p points
to
a location which contains text specified. (This was also evident from
the printf statement, which executed properly).
But When I do *(p+1) = 'M'; It should be replacing the existing text in
address pointed by p+1 -> location of character 'e' . but it again
gives an exception. If it was a read only buffer it should have given a
compile time error.


You make confusion between 'const' and 'read-only'.
Violating const gives you a warning. But litteral strings
are not const, there are read-only...

It is almost like if you where doing:
static const char no_name[]= "TestString ";
char* p= (char*) no_name;

Manipulating "TestString ", through p gives you access to
a 'read-only' object, but without the 'const' compilation
checking.

Marc Boyer
Nov 15 '05 #9
CBegin wrote:
temp static


Those two words don't go together well.
Objects with static duration are initialized before
main starts to execute and they exist until the program ends.

--
pete
Nov 15 '05 #10

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

Similar topics

1
2627
by: Jim | last post by:
Hi all, I am new to SOAP and Python. I am practicing learning SOAP with Python. I sent a request and I got the following response: <SOAPpy.Types.structType HashStringResponse at 23909440>: {}
3
1613
by: Darko Lapanje | last post by:
how can I write program who removes all ' ' from the string? dl
7
2289
by: scott289 | last post by:
I have successfully downloaded the Enterprise Library and the data access block (C#). I am able to compile and run the quickstart application. So I would like to try the DAB in a new project. But I was unable to find any instructions on referencing the neccessary DLLs in any of the Help files or walkthroughs. Did I miss it somewhere? Which DLLs do I reference? The walkthroughs seem to tell me how to use SqlHelper and such, but I cant...
7
1537
by: vee_kay | last post by:
Is there any simpler forum for C++. I feel this forum is advanced for a begineer
3
4892
by: ibm_97 | last post by:
Session 1: $db2 +c db2 => set current isolation = UR db2 => select * from t T1 ------ ABC
5
1785
by: Prem Mallappa | last post by:
Hi everybody here is my code to print all nonblank character on Input.. This program according to my knowledge should run till i press Ctrl+D but,,, this is parsing the input untill i press RETURN ( ENTER).. Why is it so.. thx in advance prem mallappa #include <stdio.h>
1
1557
by: itsjyotika | last post by:
Hello Everyone, I need to read data from a CVS file(i created it from micosoft excel) and then need to match it with the one of the date from the command line.If the date is there then it should say yes or else it should say no. I am not getting how to do this as i am just a beginer in perl. Can anybody help me in writting the code. the files r toooo.. big to be attached , so i have just shown a tiny portion of it. thanks in advance, rimjim...
5
3235
by: hn.ft.pris | last post by:
Hi: I'm a beginer of STL, and I'm wondering why none of below works: ######################################################################## .......... string str("string"); if ( str == "s" ) cout << "First character is s" << endl; OR: string str("string"); string::iterator it = str.begin();
1
1249
by: hamed steph | last post by:
i'm a beginer in programing and i need very much your help .i need explanation about while statement (loop initialization and structure of while ) also qualifier (long,short,unsigned ,signed,) type of variable (character and double). think you.......
0
9715
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
10600
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
10352
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
9175
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...
0
6867
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
5535
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
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3835
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3002
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.