473,769 Members | 2,365 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

a simple question regarding string copy

Hi,

In a small code to implement string copy:

while(*a++ = *b++) ;

both a and b are char pointers. This code works but at the end, when *a
= *b = '\0' finishes, both a and b step one block beyond the last
character of the string which is "\0" because of the "++" operation.
Will this cause memory leak?

I have tested this code with GCC, it works but will this succinct
coding cause problem later?

Thank you.

Jan 4 '07 #1
14 1752
wahaha wrote:
Hi,

In a small code to implement string copy:

while(*a++ = *b++) ;

both a and b are char pointers. This code works but at the end, when *a
= *b = '\0' finishes, both a and b step one block beyond the last
character of the string which is "\0" because of the "++" operation.
Will this cause memory leak?
It is legal in C to create a pointer that points to one past the last
element of an array as long as you don't then dereference the pointer
(which your code doesn't). I'm not sure why you might see an
opportunity for a memory leak but the code you presented is a classic
strcpy implementation example.

Robert Gamble

Jan 4 '07 #2

Robert Gamble wrote:
wahaha wrote:
Hi,

In a small code to implement string copy:

while(*a++ = *b++) ;

both a and b are char pointers. This code works but at the end, when *a
= *b = '\0' finishes, both a and b step one block beyond the last
character of the string which is "\0" because of the "++" operation.
Will this cause memory leak?

It is legal in C to create a pointer that points to one past the last
element of an array as long as you don't then dereference the pointer
(which your code doesn't). I'm not sure why you might see an
opportunity for a memory leak but the code you presented is a classic
strcpy implementation example.
I guess so. Thank you very much for your answer.

Jan 4 '07 #3
"wahaha" <zh***********@ gmail.comwrites :
In a small code to implement string copy:

while(*a++ = *b++) ;

both a and b are char pointers. This code works but at the end, when *a
= *b = '\0' finishes, both a and b step one block beyond the last
character of the string which is "\0" because of the "++" operation.
Will this cause memory leak?

I have tested this code with GCC, it works but will this succinct
coding cause problem later?
A "memory leak" occurs only when you allocate memory (e.g., by calling
malloc()) and fail to deallocate it (e.g., by calling free()). Since
your code fragment neither allocates nor deallocates any memory, it
cannot leak memory.

It could conceivably be the *cause* of a memory leak. For example, if
b points to the beginning of a malloc()ed block of memory, and you
haven't saved the value of be somewhere else before modifying it, the
fact that b has been changed means that you no longer have a way to
free() the memory (and if you try to pass the modified value of b to
free(), you'll invoke undefined behavior). So don't do that.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jan 4 '07 #4
"Keith Thompson" <ks***@mib.orgw rote in message
news:ln******** ****@nuthaus.mi b.org...
"wahaha" <zh***********@ gmail.comwrites :
>In a small code to implement string copy:

while(*a++ = *b++) ;

both a and b are char pointers. This code works but at the end, when *a
= *b = '\0' finishes, both a and b step one block beyond the last
character of the string which is "\0" because of the "++" operation.
Will this cause memory leak?

I have tested this code with GCC, it works but will this succinct
coding cause problem later?

A "memory leak" occurs only when you allocate memory (e.g., by calling
malloc()) and fail to deallocate it (e.g., by calling free()). Since
your code fragment neither allocates nor deallocates any memory, it
cannot leak memory.

It could conceivably be the *cause* of a memory leak. For example, if
b points to the beginning of a malloc()ed block of memory, and you
haven't saved the value of be somewhere else before modifying it, the
fact that b has been changed means that you no longer have a way to
free() the memory (and if you try to pass the modified value of b to
free(), you'll invoke undefined behavior). So don't do that.
Also:

http://en.wikipedia.org/wiki/Memory_leak

Dave.
Jan 4 '07 #5
I am not sure whether this code work well, for example, if some element
of b is zero before the last element is reach, then while(*a++ = *b++)
; will stop before copying the last element.
Is it true? I am not sure condition in while loop, it uses *a or a++
for exiting while loop?
chat watchara

Jan 5 '07 #6
chat wrote:
I am not sure whether this code work well, for example, if some element
of b is zero before the last element is reach, then while(*a++ = *b++)
; will stop before copying the last element.
The question was specifically about copying *strings* which by
definition are terminated by a null character (whose value is 0).
Anything past that wouldn't be part of the string and shouldn't be
copied.

Robert Gamble

Jan 5 '07 #7
On 4 Jan 2007 19:04:44 -0800, "chat" <ch***********@ gmail.comwrote:
>I am not sure whether this code work well, for example, if some element
of b is zero before the last element is reach, then while(*a++ = *b++)
; will stop before copying the last element.
Is it true? I am not sure condition in while loop, it uses *a or a++
for exiting while loop?
chat watchara
Whatever element of b contains the first 0 is BY DEFINITION the end of
the string.
Remove del for email
Jan 5 '07 #8
"chat" <ch***********@ gmail.comwrites :
I am not sure whether this code work well, for example, if some element
of b is zero before the last element is reach, then while(*a++ = *b++)
; will stop before copying the last element.
Is it true? I am not sure condition in while loop, it uses *a or a++
for exiting while loop?
What code? Please provide context when posting a followup. See
<http://cfaj.freeshell. org/google/>.

If you encounter a zero character ('\0'), that is by definition the
end of the string.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jan 5 '07 #9
chat said:
I am not sure whether this code work well, for example, if some element
of b is zero before the last element is reach, then while(*a++ = *b++)
; will stop before copying the last element.
Is it true?
No, if b is 0, it *is* the last element.
I am not sure condition in while loop, it uses *a or a++
for exiting while loop?
Neither. It uses the result of the expression *a++ = *b++

If you don't understand it, write a string-copying function that you *do*
understand.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Jan 5 '07 #10

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

Similar topics

9
2428
by: niclane | last post by:
Hi, I was reading section 5.5 of Ritchie and Kernighan and saw the following: " ..... char amessage = "now is the time"; char *pmessage = "now is the time";
17
2332
by: Ashwin | last post by:
hi guys, i have overloaded the << operator.as shown below. ostream& operator<<(ostream &out, const student &a) { out<<a.idno; out<< " " ; // out<< a.name; out<< " " ; // out<< a.marks << endl;
4
1630
by: duffdevice | last post by:
Hi, I came across this unexpected behavior while working on something else. I am attempting to return a custom type by value from a global function. I have a trace in the custom class's copy constructor, and I expected this code to tell me that the custom copy constructor had been called twice. Instead, it's only called once and the program executes correctly. Is this an optimization related to my compiler (g++ v4.0.1) or is this...
10
110304
true911m
by: true911m | last post by:
This is a simple walkthrough to get PyInstaller up and running. I decided to give PI a try, because it claims to be more selective about what it bundles into its executable files by default, and it also integrates UPX (Ultimate Packer for eXecutables) into the build process, if you have it installed. It also claims functionality on linux, as a bonus (I didn't test this). I highly recommend the UPX options, and will cover how to get it...
15
4582
by: Bjoern Schliessmann | last post by:
Hello all, I'm trying to simulate simple electric logic (asynchronous) circuits. By "simple" I mean that I only want to know if I have "current" or "no current" (it's quite digital) and the only elements need to be (with some level of abstraction to my specific problem) - sources (here begin currents) - ground (here end currents)
8
2051
by: somenath | last post by:
Hi All, I have a doubt regarding the pointer assignment . Please have a look at the following program . #include<stdio.h> #include<stdlib.h> #define NAMESIZE 10 #define SAFE_FREE(t) if(t)\ {\
14
2804
by: somenath | last post by:
Hi All, I am trying to understand the behavior of the memcpy and memmove. While doing so I wrote a program as mentioned bellow . #include<stdio.h> #include<stdlib.h> #include<string.h> #define SIZE_OF_DST 3 int main(void)
30
3544
by: galiorenye | last post by:
Hi, Given this code: A** ppA = new A*; A *pA = NULL; for(int i = 0; i < 10; ++i) { pA = ppA; //do something with pA
17
5818
by: Chris M. Thomasson | last post by:
I use the following technique in all of my C++ projects; here is the example code with error checking omitted for brevity: _________________________________________________________________ /* Simple Thread Object ______________________________________________________________*/ #include <pthread.h> extern "C" void* thread_entry(void*);
0
9586
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
9423
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,...
0
10043
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...
1
9990
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,...
0
9861
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8869
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
6672
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
5446
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2814
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.