if i do this
char *mystring="myst ring";
later i reassign to mystring like this
mystring="repla cewithnewstring ";
i'm not a c expert, but i suppose i need to get rid of the dynamically
assigned "mystring"? what should be done according to best practices ?
free(mystring) ?
tx 10 1733
slurper wrote: if i do this
char *mystring="myst ring";
later i reassign to mystring like this
mystring="repla cewithnewstring ";
i'm not a c expert, but i suppose i need to get rid of the dynamically assigned "mystring"?
There isn't one. Literal strings in C are statically allocated
constants.
what should be done according to best practices ?
Nothing.
free(mystring) ?
That results in Undefined Behaviour. If you're very lucky,
your program will crash.
If you end up in a situation where you're losing the last reference
to a string, and that string may or may not be dynamically allocated,
and you don't know which, backtrack.
--
Chris "electric hedgehog" Dollin
slurper <sl*********@ho tmail.com> writes: if i do this
char *mystring="myst ring";
later i reassign to mystring like this
mystring="repla cewithnewstring ";
i'm not a c expert, but i suppose i need to get rid of the dynamically assigned "mystring"? what should be done according to best practices ? free(mystring) ?
AFAIK this is done my the compiler, onlye if you make the following
thing:
char *mystring = malloc(9 * sizeof(char));
my_string = "mystring";
you'd have to free it, over a call to free, I think.
Kind regrads,
Nicolas
--
| Nicolas Pavlidis | Elvis Presly: |\ |__ |
| Student of SE & KM | "Into the goto" | \|__| |
| pa****@sbox.tug raz.at | ICQ #320057056 | |
|-------------------University of Technology, Graz----------------|
Nicolas Pavlidis <pa****@sbox.tu graz.at> scribbled the following: slurper <sl*********@ho tmail.com> writes: if i do this
char *mystring="myst ring";
later i reassign to mystring like this
mystring="repla cewithnewstring ";
i'm not a c expert, but i suppose i need to get rid of the dynamically assigned "mystring"? what should be done according to best practices ? free(mystring) ?
AFAIK this is done my the compiler, onlye if you make the following thing:
char *mystring = malloc(9 * sizeof(char)); my_string = "mystring";
you'd have to free it, over a call to free, I think.
No, this is wrong. The assignment my_string = "mystring"; does *NOT*
write the string "mystring" into the memory allocated by the malloc()
call. Rather, it moves the pointer my_string to point at the string
"mystring" (wherever it is stored), ignoring the memory allocated by
malloc() completely.
An attempt to call free(my_string) will cause undefined behaviour.
It is exactly if you attempted to call free("mystring" ).
Furthermore, all pointers to the memory allocated by malloc() have
gone, so it has become what I call "ghost memory", i.e. memory that is
allocated but impossible to use.
You have to look up strcpy() instead.
--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"'So called' means: 'There is a long explanation for this, but I have no
time to explain it here.'"
- JIPsoft
Joona I Palaste wrote: Nicolas Pavlidis <pa****@sbox.tu graz.at> scribbled the following: slurper <sl*********@ho tmail.com> writes: if i do this
char *mystring="myst ring";
later i reassign to mystring like this
mystring="repla cewithnewstring ";
i'm not a c expert, but i suppose i need to get rid of the dynamically assigned "mystring"? what should be done according to best practices ? free(mystring) ? AFAIK this is done my the compiler, onlye if you make the following thing:
char *mystring = malloc(9 * sizeof(char)); my_string = "mystring";
you'd have to free it, over a call to free, I think.
No, this is wrong. The assignment my_string = "mystring"; does *NOT* write the string "mystring" into the memory allocated by the malloc() call. Rather, it moves the pointer my_string to point at the string "mystring" (wherever it is stored), ignoring the memory allocated by malloc() completely. An attempt to call free(my_string) will cause undefined behaviour. It is exactly if you attempted to call free("mystring" ). Furthermore, all pointers to the memory allocated by malloc() have gone, so it has become what I call "ghost memory", i.e. memory that is allocated but impossible to use. You have to look up strcpy() instead.
tx for answers so far
but i used string literals here, but suppose i use fgets in a loop to
process all lines in a file. i store the lines in a variable (char*
mystring). each line is assigned to the string variable. but what happens
with the strings allocated to it earlear?
for example:
char* mystring;
FILE *stream;
if((stream = fopen ("filename", "r")) != (FILE *)0) {
while((fgets(my string, 1023, stream)) != (char *)0 ) {
<process each line>
}
} else {
<do fopen error handling>
}
but what happens with the strings i assign to mystring? will i end up with
the whole file except the last line in memory, without references to it?
i don't think C will delete it automatically, because if i say in the loop
char* anotherstring=m ystring, i'll end up with two references to the same
string and the compiler can't know the string is still referenced by
another variable.
slurper <sl*********@ho tmail.com> scribbled the following: Joona I Palaste wrote: No, this is wrong. The assignment my_string = "mystring"; does *NOT* write the string "mystring" into the memory allocated by the malloc() call. Rather, it moves the pointer my_string to point at the string "mystring" (wherever it is stored), ignoring the memory allocated by malloc() completely. An attempt to call free(my_string) will cause undefined behaviour. It is exactly if you attempted to call free("mystring" ). Furthermore, all pointers to the memory allocated by malloc() have gone, so it has become what I call "ghost memory", i.e. memory that is allocated but impossible to use. You have to look up strcpy() instead.
tx for answers so far but i used string literals here, but suppose i use fgets in a loop to process all lines in a file. i store the lines in a variable (char* mystring). each line is assigned to the string variable. but what happens with the strings allocated to it earlear?
If you are indeed assigning the line to a string variable with the =
operator, instead of strcpy() or a similar function, then the previous
value is simply ignored. It is as if your code has:
int a;
a=1;
a=2;
and then you're asking what happens to 1 after the third line.
Now, is it a bad thing that the previous values are ignored? It depends
on how they were initially created. If they were string literals, such
as:
mystring = "Hello world!";
then it's entirely OK, because string literals have program-wide
storage, and the compiler will automatically claim them up when the
program exits. However, if you used malloc() to allocate memory for
them, for example:
mystring = malloc(9); /* no need for sizeof(char) as it is always 1 */
then you get what I called "ghost memory", i.e. a memory leak.
for example: char* mystring;
You should use malloc() to allocate some memory to store into mystring
here.
FILE *stream; if((stream = fopen ("filename", "r")) != (FILE *)0) { while((fgets(my string, 1023, stream)) != (char *)0 ) {
This fgets() call does *NOT* assign a new value to mystring at all.
The same value - i.e. the same memory location - is reused over and
over again. Only the *contents* of that memory location change.
Therefore it is entirely safe to overwrite the previous line with the
next, without free()ing it. Actually, trying to free() it *would* be
wrong, because then the next fgets() call would try to read data into
unallocated memory.
<process each line>
What does this <process each line> contain? Does it have any statements
of the form
mystring = /* ... */;
? If it doesn't, you're all OK, fine, kosher, hunky-dory. If it *does*,
though, then you have to be careful not to end up with memory leaks.
} } else { <do fopen error handling> } but what happens with the strings i assign to mystring? will i end up with the whole file except the last line in memory, without references to it?
By the looks of it, I'd guess not. A definite not if my experience is of
any use. It all depends on what you do in the <process each line> that
you did not show. But if we ignore the <process each line>, then the
above code is completely OK, as long as you remember to actually
allocate some memory for mystring to point to. You should not end up
with the whole file except the last line in memory if my intuition about
your not shown code is of any good. Only the last line should remain in
memory.
i don't think C will delete it automatically, because if i say in the loop char* anotherstring=m ystring, i'll end up with two references to the same string and the compiler can't know the string is still referenced by another variable.
This won't matter. If you are indeed using the same value for mystring
over and over again, as I suspect you are, then char *anotherstring =
mystring will simply reuse the same value for anotherstring over and
over again too. Both variables are *always* pointing to the *same*
memory location. You can then later call free(mystring) or
free(anotherstr ing) - BUT NOT BOTH - to free up the allocated memory.
--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"This is a personnel commuter."
- Train driver in Scientific American
slurper wrote: tx for answers so far but i used string literals here, but suppose i use fgets in a loop to process all lines in a file. i store the lines in a variable (char* mystring). each line is assigned to the string variable. but what happens with the strings allocated to it earlear? for example: char* mystring; FILE *stream; if((stream = fopen ("filename", "r")) != (FILE *)0) { while((fgets(my string, 1023, stream)) != (char *)0 ) {
`mystring` doesn't point anywhere, so at this point you get Undefined
Behaviour.
In this example you could perfectly happily do
char mystring[1023];
and
fgets( mystring, sizeof mystring, stream )
<process each line> } } else { <do fopen error handling> } but what happens with the strings i assign to mystring? will i end up with the whole file except the last line in memory, without references to it?
No. You didn't allocate any memory, so it won't grow.
If you don't need to keep all the strings you read, allocate `mystring`
once - either as a local array, or with a call to `malloc` (and a matching
`free` when you're done). If you *do* need to keep all the strings you read,
then mallocate per line (and free them all when you're done).
i don't think C will delete it automatically, because if i say in the loop char* anotherstring=m ystring, i'll end up with two references to the same string and the compiler can't know the string is still referenced by another variable.
Yes.
--
Chris "electric hedgehog" Dollin
slurper wrote: if i do this
char *mystring="myst ring";
later i reassign to mystring like this
mystring="repla cewithnewstring ";
i'm not a c expert, but i suppose i need to get rid of the dynamically assigned "mystring"? what should be done according to best practices ? free(mystring) ?
In the context of pointer assignment,
the string literal is converted to a pointer to
an array which resides in memory.
The duration of that array, is until the end of the program.
If you don't use a function like malloc or something similar,
then you're not dealing with dynamic allocation.
Identical string literals may refer to same or different objects.
The exprsssion
("mystring" == "mystring")
may be true in one part of a program
and false in another part of the same program.
--
pete
slurper wrote: if i do this
char *mystring="myst ring";
later i reassign to mystring like this
mystring="repla cewithnewstring ";
Yep.
i'm not a c expert, but i suppose i need to get rid of the dynamically assigned "mystring"? what should be done according to best practices ? free(mystring) ?
No. "mystring" has static storage duration - it cannot be released. It is
not dynamically allocated like memory from malloc() - next time the
function is called (or the scope entered, or whatever) the pointer will be
set to the same string, not a newly allocated one. tx
Nicolas Pavlidis wrote: slurper <sl*********@ho tmail.com> writes:
if i do this
char *mystring="myst ring";
later i reassign to mystring like this
mystring="repla cewithnewstring ";
i'm not a c expert, but i suppose i need to get rid of the dynamically assigned "mystring"? what should be done according to best practices ? free(mystring) ?
AFAIK this is done my the compiler, onlye if you make the following thing:
char *mystring = malloc(9 * sizeof(char)); my_string = "mystring";
you'd have to free it, over a call to free, I think.
First, mystring and my_string are different identifiers. Second, this is a
memory leak - assigning the address of "mystring" will overwrite the
address of the malloced memory, which can no longer be freed. You probably
meant:
char *mystring = malloc(9); /* sizeof(char) == 1 */
strcpy(mystring , "mystring") ;
/* do something with mystring */
free(mystring); This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Krakatioison |
last post by:
My sites navigation is like this:
http://www.newsbackup.com/index.php?n=000000000040900000
, depending on the variable "n" (which is always a number), it will take me
anywhere on the site... this number is always changing as I have hundreds of
thousand of pages of text on my site.
Problem:
- in my opinion this just not only look weird, but the variable "n" (number)
|
by: Stu Cazzo |
last post by:
I have the following:
String myStringArray;
String myString = "98 99 100";
I want to split up myString and put it into myStringArray.
If I use this:
myStringArray = myString.split(" ");
it will split myString up using the delimiter of 1 space
so that
|
by: John F Dutcher |
last post by:
I use code like the following to retrieve fields from a form:
recd =
recd.append(string.ljust(form.getfirst("lname",' '),15))
recd.append(string.ljust(form.getfirst("fname",' '),15))
etc., etc.
The intent is to finish by assigning the list to a string that I would
write to disk: recstr = string.join(recd,'')
|
by: Angus Leeming |
last post by:
Hello,
Could someone explain to me why the Standard conveners chose to typedef
std::string rather than derive it from std::basic_string<char, ...>?
The result of course is that it is effectively impossible to forward declare
std::string. (Yes I am aware that some libraries have a string_fwd.h header,
but this is not portable.)
That said, is there any real reason why I can't derive an otherwise empty
|
by: Andrew |
last post by:
I have written two classes : a String Class based on the book " C++ in
21 days " and a GenericIpClass listed below :
file GenericStringClass.h
// Generic String class
| |
by: zoro |
last post by:
Hi,
I am new to C#, coming from Delphi. In Delphi, I am using a 3rd party
string handling library that includes some very useful string
functions, in particular I'm interested in BEFORE (return substring
before a pattern), AFTER (return substring after a pattern), and
BETWEEN (return substring between 2 patterns).
My questions are:
1. Can any tell me how I can implement such functionality in C#?
2. Is it possible to add/include function...
|
by: Badass Scotsman |
last post by:
Hello,
Using VB and ASP,NET I would like to be able to search a STRING for a
smaller STRING within, based on the characters which appear before and
after.
For example:
String1 = " That was a tasty burger"
|
by: morleyc |
last post by:
Hi, i would like to remove a number of characters from my string (\t
\r \n which are throughout the string), i know regex can do this but i
have no idea how. Any pointers much appreciated.
Chris
|
by: ramu |
last post by:
Hi,
Suppose I have a string like this:
"I have a string \"and a inner string\\\" I want to remove space in
this string but not in the inner string"
In the above string I have to remove spaces, but not in the inner
string(\"and a inner string\\\"). Will anyone please tell me how to do
this?
|
by: drjay1627 |
last post by:
hello,
This is my 1st post here!
*welcome drjay*
Thanks! I look answering questions and getting answers to other!
Now that we got that out of the way. I'm trying to read in a string and add the unique words in the string to a map. Eg:
|
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...
| |
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
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...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |