473,756 Members | 8,132 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 #1
74 4681
ballpointpenthi ef said:
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.


When you allocate the memory, you know precisely how much memory you are
requesting.

Don't Forget (tm).

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
May 3 '06 #2
"ballpointpenth ief" <Ma************ *@gmail.com> writes:
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?


Your code allocated the memory.
Your code should remember how much it allocated.

--
Chris.
May 3 '06 #3

"Chris McDonald" <ch***@csse.uwa .edu.au> wrote
"ballpointpenth ief" <Ma************ *@gmail.com> writes:
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?


Your code allocated the memory.
Your code should remember how much it allocated.


If I understand what I've learned today, if one has a differing module other
than the one in which
p = malloc(some number);
is declared and in which memory is a burning question, then ones source
needs to declare and pass. Joe
---------
A guy says to me yesterday, if Washington hadn't crossed the Delaware in
___, then we would be paying taxes to the Queen.
But I like Elizabeth.
May 3 '06 #4
"Joe Smith" <gr**********@n etzero.net> writes:
"Chris McDonald" <ch***@csse.uwa .edu.au> wrote
"ballpointpenth ief" <Ma************ *@gmail.com> writes:
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?
Your code allocated the memory.
Your code should remember how much it allocated.

If I understand what I've learned today, if one has a differing module other
than the one in which
p = malloc(some number);
is declared and in which memory is a burning question, then ones source
needs to declare and pass. Joe


(now, If I'm understanding you correctly) Yes, if some other code (for
which you perhaps don't have the code) performs the allocation, then if
your code needs to iterate over the memory, your code needs to know the
allocated size.

You will typically need to indicate how much memory the other routine
should allocate, or it should inform your code how much it did allocate.

In short, you cannot determine the allocated size, from the allocated
memory itself.

--
Chris.
May 3 '06 #5
Chris McDonald wrote:
"Joe Smith" <gr**********@n etzero.net> writes:
"Chris McDonald" <ch***@csse.uwa .edu.au> wrote
.... snip ...
Your code allocated the memory.
Your code should remember how much it allocated.
If I understand what I've learned today, if one has a differing
module other than the one in which
p = malloc(some number);
is declared and in which memory is a burning question, then ones
source needs to declare and pass. Joe

.... snip ...
In short, you cannot determine the allocated size, from the
allocated memory itself.


However, you can determine how much memory is needed by some means
or other, and perform a realloc to that size. This can lead to
snarling dogs playing tug-of-war.

--
"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 3 '06 #6
In article <eJ************ *************** ***@bt.com>,
Richard Heathfield <in*****@invali d.invalid> wrote:
ballpointpenthi ef said:
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.


When you allocate the memory, you know precisely how much memory you are
requesting.

Don't Forget (tm).


However when you allocate the memory, you don't know precisely how much
you received. It could be more than you requested. And common
applications exist which could make use of that extra memory if only
they knew it existed (e.g. a dynamic array).

Major OS's provide this functionality in a non-portable fashion. Imho C
should provide a portable layer over this functionality.

-Howard
May 3 '06 #7
Howard Hinnant wrote:
In article <eJ************ *************** ***@bt.com>,
Richard Heathfield <in*****@invali d.invalid> wrote:
ballpointpenthi ef said:
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. When you allocate the memory, you know precisely how much memory you are
requesting.

Don't Forget (tm).


However when you allocate the memory, you don't know precisely how much
you received. It could be more than you requested. And common
applications exist which could make use of that extra memory if only
they knew it existed (e.g. a dynamic array).

Why would they make use of more memory than they requested instead of
just requesting that much memory in the first place ?
Major OS's provide this functionality in a non-portable fashion. Imho C
should provide a portable layer over this functionality.

No.
How horrible.
May 4 '06 #8
In article <44********@new s.wineasy.se>,
"Nils O. Selåsdal" <no******@asgaa rd.homelinux.or g> wrote:
However when you allocate the memory, you don't know precisely how much
you received. It could be more than you requested. And common
applications exist which could make use of that extra memory if only
they knew it existed (e.g. a dynamic array).
Why would they make use of more memory than they requested instead of
just requesting that much memory in the first place ?


Perhaps I should elucidate "dynamic array".

Consider a general purpose library which manages an array of short.
This array has a length to be determined at run time, and that length
can grow or shrink over the lifetime of the array via functions such as
"insert", "resize" or "append".

A typical use case might be:

struct array_of_short
{
short* data;
size_t size;
};

array_of_short my_array = create_array_sh ort(N);
// ...
// Fill my_array with values and do some computation with it
// ...
if (some_condition )
{
append_array_sh ort(&my_array, M, value);
// ...
// continue computation with modified array
// ...
}

The data structure as described above has an efficiency concern:
Repeated growth in size can lead to quadratic expense due to continually
reallocating for a slightly larger size. A well known fix is to have
the array keep track of both a logical size and a physical capacity
which it can cheaply grow into:

struct array_of_short
{
short* data;
size_t size;
size_t capacity;
};

Use as before, but this new struct has an invariant: size <= capacity.

"append_array_s hort" and its brethren can now increase the size very
rapidly if the new size is still less than the capacity. When the new
size is greater than the capacity, these functions can reallocate the
capacity at a geometric rate (say by some growth factor between 1.5 and
2, (1+sqrt(5))/2 has been theorized as an optimum growth factor). Using
a geometric growth factor for the capacity bounds the number of
reallocations that a given array will see over its lifetime to a very
small number (compared to an incremental growth strategy).

No matter what the growth strategy for capacity, its existence is a
major motivation for finding out the amount of memory actually
allocated. create_array_sh ort(N) may request only N*sizeof(short)
bytes, but may receive slightly more than that (for alignment purposes
or whatever). If create_array_sh ort(N) had some way to find out how
much memory it actually received, then it makes perfect sense to set
capacity to size_received/sizeof(short) instead of to N. It makes for
higher performing code in the average case.

-Howard
May 4 '06 #9
[snips]

On Thu, 04 May 2006 14:18:31 +0000, Howard Hinnant wrote:
The data structure as described above has an efficiency concern:
Repeated growth in size can lead to quadratic expense due to continually
reallocating for a slightly larger size.


So don't do that. In simplest terms, don't add, multiply.

Assume you're adding, oh, 100 elements at each step, and starting with
1000. I'm not going to add, I'm going to scale, by 25%. By the time
you've _doubled_ your storage, mine's gone up by a factor of almost ten,
yet the _worst_ waste I will ever have is 25% of the total elements, minus
one element.

Other scaling factors work, too. Need to be more conservative? Scale by
5 or 10 per cent. Need memory to grow faster? Try 50%. Or even 100%.

Increasing by a static amount - adding 100 units at each step, etc -
strikes me as a tad silly.
May 4 '06 #10

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
13009
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
1050
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
2590
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
3481
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
20783
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
24781
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
2042
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
9456
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
9275
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
10040
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
9873
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
9846
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
9713
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
8713
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
7248
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...
3
2666
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.