473,785 Members | 2,291 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sizeof([ALLOCATED MEMORY])

If I have malloc()'ed a pointer and want to read from it as if it were
an array, I need to know that I won't be reading past the last index.

If this is a pointer to a pointer, a common technique seems to be
setting a NULL pointer to the end of the list, and here we know that
the allocated memory has been exhausted. All good.

When this is a pointer to another type, say int, I could have a
variable that records how much memory is being allocated and use that
to track the size of the 'array'.
Alternatively, we could set the end of the 'array' to some kind of
error-code, such as 99 or MAX_INT.
I don't like either of these techniques.

So, what is a good way to stop a loop reading or writing past the
memory allocated to a pointer?
Or if possible, what is a good way of determining the size of memory
allocated to a pointer?

Cheers,
Matt

May 3 '06
74 4699
On Tue, 16 May 2006 07:58:28 GMT, "Tomás" <NU**@NULL.NULL > wrote:
while ( *dest = *source ) ++dest, ++source;


This one doesn't do a redundant final incrementation.

for(;*dest = *source;++dest, ++source);

Nor does this one.

while ( *dest++ = *source++ );

This one does however.

for(;*dest++ = *source++;);

As does this one.
-Tomás


Dont jump too fast to conclusions:

for(;*dest=*sou rce;++dest,++so urce);

is compiled under one very popular compiler as the following flow in
pseudo-code

JUMPTO :TEST:
:LOOP:
READ dest
INC
STORE dest
READ source
INC source
STORE source
:TEST:
READ source
READ @source
READ dest
STORE @dest
IFNOTZERO JUMPTO :LOOP:

for(;*dest++=*s ource++;);

is compiled under same compiler as the following flow in pseudo-code

:LOOP:
READ source
READ @source
INC source
STORE source
READ dest
STORE @dest
INC dest
STORE @dest
IFNOTZERO JUMPTO :LOOP:

Which is more optimized in code-size and, probably, also in time.
"Let the profiler tell you" is good advice, always.

Best regards,

Zara
May 16 '06 #61
"Tomás" wrote:
pete posted:
There are some style guidlines against writing code like this:
while (*dest++ = *source++);
because it looks like an accident.


while (*dest++ = *source++); /* Not an accident */


Not only have you fouled up the attributions, but you have fouled
the quote. It is considered very bad form to edit quotations. I
actually wrote:

while (*dest++ = *source++) continue;

as an analogy to something else.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>
Also see <http://www.safalra.com/special/googlegroupsrep ly/>
May 16 '06 #62
Tomás wrote:
while ( *dest = *source ) ++dest, ++source;


This one doesn't do a redundant final incrementation.
for(;*dest = *source;++dest, ++source);


Nor does this one.
while ( *dest++ = *source++ );


This one does however.
for(;*dest++ = *source++;);


As does this one.


Yet as was noted by the person posting them, they all produced the same
machine code thus illustrating that there is no point in selecting one
for reasons of efficiency. At least, not unless you have verified that
on your implementation it really will be more efficient.

No doubt this was in a situation where dest and source were not used
after the loop.
--
Flash Gordon, living in interesting times.
Web site - http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro:
http://clc-wiki.net/wiki/Intro_to_clc
May 16 '06 #63
CBFalconer wrote:
"Tomás" wrote:
pete posted:
There are some style guidlines against writing code like this:
while (*dest++ = *source++);
because it looks like an accident.

while (*dest++ = *source++); /* Not an accident */


Not only have you fouled up the attributions, but you have fouled
the quote. It is considered very bad form to edit quotations. I
actually wrote:

while (*dest++ = *source++) continue;

as an analogy to something else.


You've made a mistake, Chuck. Tomas was replying to pete, not you, and
pete did post the quoted material.
--
Flash Gordon, living in interesting times.
Web site - http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro:
http://clc-wiki.net/wiki/Intro_to_clc
May 16 '06 #64
Flash Gordon wrote:
CBFalconer wrote:
"Tomás" wrote:
pete posted:

There are some style guidlines against writing code like this:
while (*dest++ = *source++);
because it looks like an accident.
while (*dest++ = *source++); /* Not an accident */


Not only have you fouled up the attributions, but you have fouled
the quote. It is considered very bad form to edit quotations. I
actually wrote:

while (*dest++ = *source++) continue;

as an analogy to something else.


You've made a mistake, Chuck. Tomas was replying to pete, not you, and
pete did post the quoted material.


Could well be. It is threaded here as a reply to me, and was
received before the pete article arrived. Netscape is known to
have anomalies when the References chain grows too long. So when I
saw that the only article with that phrase in it was mine, which
included the 'continue'. Apologies to Tomas.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>
Also see <http://www.safalra.com/special/googlegroupsrep ly/>
May 16 '06 #65
CBFalconer posted:
Apologies to Tomas.

No problem.
(Which reminds me I've to upgrade to the lastest version of XNews some
time soon... )
-Tomás
May 16 '06 #66
> Not necessarily. Consider the hypothetical "one time use"
allocater. realloc need only allocate a new chunk of the
appropriate size and copy the old over. It doesn't need to know
the size of the old, even for the copying if it can detect 'the
end' by some other means, analogous to encountering EOF.


For the extended malloc interface we should see how malloc is
implemented to see if size information is there and is fast to obtain.

I don't know any malloc implementation that does not store the size. So
if the size is there in all known implementations , it's logical to
propose new functions. If all known malloc implementations (check every
C library out there to check this) store the size, I think that we
should use that information to get better performance and less memory
use.

Maybe obtaining the size is not constant time in the "one time use"
allocator and you must do something similar to "strlen()", but let's be
practical: there is not such allocator in the real world, and I doubt
it will ever exist.

So let's asume that the size information is there and is very cheap to
obtain. Now we can discuss if proposed functions improve performance or
not, or they are useful enough enough to include them in the standard.
I can understand that you can think that those advanced reallocation
functions are not useful because you might never need them for general
purpose C programming. I think that memory reallocation is a common
pattern for a lot of C programs, and that there is an easy way to
improve their performance through these functions.

Regards,

Ion

May 16 '06 #67
"Tomás" wrote:
CBFalconer posted:
Apologies to Tomas.


No problem.

(Which reminds me I've to upgrade to the lastest version of XNews
some time soon... )


Your posts are invariably threaded to the wrong parent, and I
suspect the reference headers are fouled and incorrectly
truncated. This could well be caused by Xnews, which I understand
to be fairly reliable in general. So I encourage the upgrade.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>
Also see <http://www.safalra.com/special/googlegroupsrep ly/>
May 16 '06 #68
"Ion Gaztañaga" <ig********@gma il.com> wrote in message
news:11******** **************@ j55g2000cwa.goo glegroups.com.. .
Not necessarily. Consider the hypothetical "one time use"
allocater. realloc need only allocate a new chunk of the
appropriate size and copy the old over. It doesn't need to know
the size of the old, even for the copying if it can detect 'the
end' by some other means, analogous to encountering EOF.
For the extended malloc interface we should see how malloc is
implemented to see if size information is there and is fast to obtain.

I don't know any malloc implementation that does not store the size. So
if the size is there in all known implementations , it's logical to
propose new functions. If all known malloc implementations (check every
C library out there to check this) store the size, I think that we
should use that information to get better performance and less memory
use.


<OT>
For most implementations , the size of the allocated block is trivially easy
to discover -- it's usually a few bytes before the address malloc() or
realloc() returns. Check the implementations that you care about, put in
#ifdefs that detect those implementations and deal with them, and leave in
some portable code to handle everything else.
</OT>
Maybe obtaining the size is not constant time in the "one time use"
allocator and you must do something similar to "strlen()", but let's be
practical: there is not such allocator in the real world, and I doubt
it will ever exist.


IIRC, such an allocator was recommended on clc the other day to someone
whose normal malloc() didn't fit on an embedded system with only a few kB of
memory. I'm pretty sure someone, somewhere has implemented such before
because it's useful in certain cases.

S

--
Stephen Sprunk "Stupid people surround themselves with smart
CCIE #3723 people. Smart people surround themselves with
K5SSS smart people who disagree with them." --Aaron Sorkin
*** Posted via a free Usenet account from http://www.teranews.com ***
May 17 '06 #69
On Tue, 16 May 2006 07:58:28 UTC, "Tomßs" <NU**@NULL.NULL > wrote:
while ( *dest = *source ) ++dest, ++source;
This one doesn't do a redundant final incrementation.


Says who? One of the mashines I had do use such loop it had an extra
cost of dest--, source--; at the end of the loop. The cause: the
mashine had an mashine code like

*dest++ = *source++;

as single memory to memory instruction, but not equivalent without the
increments.
So to get the final pointers right both hand needed an separate
decrement to fit the "as if" clause.
for(;*dest = *source;++dest, ++source);

Nor does this one.


Says who? See above.
while ( *dest++ = *source++ );

This one does however.


Best optimum because 'as if' qualifies as 'really done'. Except: don't
save spaces!
while (*dest++ = *source++) ;
= that little space helps to see that
the body is empty. More readable would be: bring the semicolon on the
next line on one more indention.
for(;*dest++ = *source++;);

As does this one.


Yep.

As I found out since about 1990: save typing but don't save on
meaningfull comments so good as possible and let the copiler do the
optimising on mashine code level. It will do better as you ever will
get it in acceptable time.

Meaningfull comments needed for maintenance after haing the code
untouched for 12 month or longer. Save typing means: write compact
code without consideration of beginners in programming but don't
require with real experts with more than 5 years extensive experience.

Don't mircro optimazion by hand because the next compiler version may
turn back that in its absolute contrary. Rethink the algorithm you use
will give a better optimazion anyway.

Use the highest possible warning level even on the final compile with
highest optimazion, remove any diagnostic the compiler may give by
resolving the cause - but use casts only when you have rethinking the
logic and you knows exactly that you knows absolutely that you knows
exactly why you have to cast and there is nothing else that can be
done, but never cast when it is only to get the compiler quiet.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!

May 17 '06 #70

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

Similar topics

0
2048
by: Andreas Suurkuusk | last post by:
Hi, I just noticed your post in the "C# memory problem: no end for our problem?" thread. In the post you implied that I do not how the garbage collector works and that I mislead people. Since the thread is over a month old, I decided to start a new one with my response. Please see my comments inline.
4
13012
by: Frank Esser | last post by:
I am using SQL 8 Personal edition with sp2 applied. I set the max server memory to 32MB and leave the min server memory at 0. When my application starts hitting the database hard the memory usage reported through task manager peaks between 41-42MB. I've stopped and restarted the MSSQLserver service and checked that the running values are what I set them to be. Does anybody have any ideas as to why the sqlservr.exe would be utilizing more...
0
1053
by: Bill Burwell | last post by:
Which memory properties, or what combinations of memory properties, provide useful information about a program's memory usage when that program has just started leaking memory? While I have a VB bias, it seems to me the answer to this question should be generic - that is language independent.
4
2591
by: Franklin Lee | last post by:
Hi All, I use new to allocate some memory,even I doesn't use delete to release them. When my Application exit, OS will release them. Am I right? If I'm right, how about Thread especally on Solaries OS? This means that I use new to allocate memory in one Thread and doesn't use delete to release them.
9
2354
by: Mike P | last post by:
I know everything about reference counting and making sure you don't have large objects lying around. I have also profiled my app with multiple tools. I know about the fact GC collects memory but not necessary give it back to the OS. It seems that .NET win app will only return memory to the OS when the OS is asking for it. But!!! When the OS is asking for it is usually too late, tons of swapping and slow performance.
22
3484
by: xixi | last post by:
hi, we are using db2 udb v8.1 for windows, i have changed the buffer pool size to accommadate better performance, say size 200000, if i have multiple connection to the same database from application server, will each connection take the memory 800M (200000 x 4k = 800 M), so the memory took will be 800M times number of connections, or the total memory get from bufferpool will be 800M?
14
20786
by: Alessandro Monopoli | last post by:
Hi all, I'm searching a PORTABLE way to get the available and total physical memory. Something like "getTotalMemory" and it returns the memory installed on my PC in bytes, and "getAvailableMemory" and it returns the available memory in bytes. Do you know is there's a C function, a c++ Object or anything else that compiles in Linux and Windows to get these data?
5
24811
by: kumarmdb2 | last post by:
Hi guys, For last few days we are getting out of private memory error. We have a development environment. We tried to figure out the problem but we believe that it might be related to the OS (I am new to Windows so not sure). We are currently bouncing the instance to overcome this error. This generally happen at the end of business day only (So maybe memory might be getting used up?). We have already increased the statement heap & ...
1
2047
by: Jean-Paul Calderone | last post by:
On Tue, 22 Apr 2008 14:54:37 -0700 (PDT), yzghan@gmail.com wrote: The test doesn't demonstrate any leaks. It does demonstrate that memory usage can remain at or near peak memory usage even after the objects for which that memory was allocated are no longer live in the process. This is only a leak if peak memory goes up again each time you create any new objects. Try repeated allocations of a large dictionary and observe how memory...
5
505
by: cham | last post by:
Hi, I am working on c++ in a linux system ( Fedora core 4 ), kernel version - 2.6.11-1.1369_FC4 gcc version - 4.0.0 20050519 ( Red Hat 4.0.0-8 ) In my code i am creating a vector to store pointers of type structure "SAMPLE_TABLE_STRUCT" ( size of this structure is 36 bytes ). I create an instance of structure "SAMPLE_TABLE_STRUCT" using operator "new" and push back into the vector,this is done inside a for loop for
0
9491
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
10357
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...
1
10104
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
9959
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
8988
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
6744
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();...
1
4063
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
2
3668
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
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.