473,471 Members | 4,625 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

how to figure out the size of buffer returned by malloc

Hi,
If I have the folllowing:

char* p = malloc(5);
memset(p,-1,5);
*p = 0;
printf("%d\n",strlen(p));
free(p);

It will print 0. Is there a way to retrive the initial size of memory
returned by malloc? Other than using an extra variable to hold the
initial size like:

size_t i = 5;
char* p = malloc(i);
....

The initial requested size is then stored in i. Is there a
end-of-malloc-marker?

Thanks!
Nov 14 '05 #1
10 2287
pe********@yahoo.com (pembed2003) wrote in
news:db**************************@posting.google.c om:
Hi,
If I have the folllowing:

char* p = malloc(5);
memset(p,-1,5);
*p = 0;
printf("%d\n",strlen(p));
free(p);

It will print 0. Is there a way to retrive the initial size of memory
returned by malloc? Other than using an extra variable to hold the
initial size like:

size_t i = 5;
char* p = malloc(i);
No. You must track it yourself.
The initial requested size is then stored in i. Is there a
end-of-malloc-marker?


Not that C knows about.

--
- Mark ->
--
Nov 14 '05 #2

"pembed2003" <pe********@yahoo.com> wrote in message
news:db**************************@posting.google.c om...
Hi,
If I have the folllowing:

char* p = malloc(5);
memset(p,-1,5);
*p = 0;
printf("%d\n",strlen(p));
Should be:

printf("%lu\n", (unsigned long)strlen(p));
free(p);

It will print 0. Is there a way to retrive the initial size of memory
returned by malloc?
'malloc()' does not return the size of what it allocates,
but a pointer to it.

The only guarantee you have is that 'malloc()' (if it succeeds,
indicated by non-NULL return value), will allocate *at least* the
number of bytes requested. It's allowed to allocate more (but
you must not access more than you requested).
Other than using an extra variable to hold the
initial size like:

size_t i = 5;
char* p = malloc(i);
...

The initial requested size is then stored in i. Is there a
end-of-malloc-marker?


No. But you can easily 'simulate' one by adding one more
byte to your requested size, and storing some special 'sentinel'
value there, e.g.:

size_t size = 5;
char marker(0xFF);
char *p = malloc(size + 1);
*(p + size) = marker;

What are you trying to do?

-Mike
Nov 14 '05 #3
pembed2003 wrote:
Hi,
If I have the folllowing:

char* p = malloc(5);
memset(p,-1,5);
*p = 0;
printf("%d\n",strlen(p));
free(p);

It will print 0. Is there a way to retrive the initial size of memory
returned by malloc? Other than using an extra variable to hold the
initial size like:

size_t i = 5;
char* p = malloc(i);
...

The initial requested size is then stored in i. Is there a
end-of-malloc-marker?


This is Question 7.27 in the comp.lang.c Frequently
Asked Questions (FAQ) list

http://www.eskimo.com/~scs/C-faq/top.html

See also Question 7.26.

--
Er*********@sun.com

Nov 14 '05 #4
pembed2003 wrote:

Hi,
If I have the folllowing:

char* p = malloc(5);
memset(p,-1,5);
*p = 0;
printf("%d\n",strlen(p));
free(p);

It will print 0.
That's good.
Is there a way to retrive the initial size of memory
returned by malloc?
http://www.eskimo.com/~scs/C-faq/q7.27.html

Other than using an extra variable to hold the initial size


That's pretty much the only way portably.

Brian Rodenborn
Nov 14 '05 #5
pe********@yahoo.com (pembed2003) wrote in message news:<db**************************@posting.google. com>...
Hi,
If I have the folllowing:

char* p = malloc(5);
memset(p,-1,5);
*p = 0;
printf("%d\n",strlen(p));
free(p);

It will print 0. Is there a way to retrive the initial size of memory
returned by malloc? Other than using an extra variable to hold the
initial size like:

size_t i = 5;
char* p = malloc(i);
...

The initial requested size is then stored in i. Is there a
end-of-malloc-marker?

Thanks!


You keep track of this in your program.
But implementations of malloc do provide ways
of figuring out the size allocated by malloc.
However, this is non-portable since standard C's
malloc does not mention of a way to do this.

For example though, with Doug Lea's malloc, you
can get the size by inspecting the address returned - 4
which contains the size allocated. Though this is off
topic.

--
nethlek
Nov 14 '05 #6
"Mike Wahler" <mk******@mkwahler.net> wrote in message news:<AH******************@newsread1.news.pas.eart hlink.net>...
"pembed2003" <pe********@yahoo.com> wrote in message
news:db**************************@posting.google.c om...
Hi,
If I have the folllowing:

char* p = malloc(5);
memset(p,-1,5);
*p = 0;
printf("%d\n",strlen(p));


Should be:

printf("%lu\n", (unsigned long)strlen(p));
free(p);

It will print 0. Is there a way to retrive the initial size of memory
returned by malloc?


'malloc()' does not return the size of what it allocates,
but a pointer to it.

The only guarantee you have is that 'malloc()' (if it succeeds,
indicated by non-NULL return value), will allocate *at least* the
number of bytes requested. It's allowed to allocate more (but
you must not access more than you requested).
Other than using an extra variable to hold the
initial size like:

size_t i = 5;
char* p = malloc(i);
...

The initial requested size is then stored in i. Is there a
end-of-malloc-marker?


No. But you can easily 'simulate' one by adding one more
byte to your requested size, and storing some special 'sentinel'
value there, e.g.:

size_t size = 5;
char marker(0xFF);
char *p = malloc(size + 1);
*(p + size) = marker;

What are you trying to do?


Thanks for everyone who answered my question. To answer Mike's
question:

I don't really have the "need" to do that yet but I am wondering how
does 'free' know how many bytes to free? For example:

char* s = malloc(10);
free(s); // how many bytes to free?

How does free know how many bytes to free? I have heard that malloc
also allocate additional memory to hold some header information. Where
is this header information stored? If we have access to the header, we
can find that out?

Thanks!
Nov 14 '05 #7
pembed2003 wrote:
[...]
I don't really have the "need" to do that yet but I am wondering how
does 'free' know how many bytes to free? For example:

char* s = malloc(10);
free(s); // how many bytes to free?

How does free know how many bytes to free? I have heard that malloc
also allocate additional memory to hold some header information. Where
is this header information stored? If we have access to the header, we
can find that out?


The actual size of the memory pointed to by `s' is
etched in mystic runes on a tablet of finest jade, kept
in a diamond-encrusted box with silver hinges and golden
locks, hidden in a sacred cave in the Tibetan highlands
and guarded by a crack regiment of three hundred Abominable
Snowmen, each mounted upon a hippogriff with carnivorous
tendencies. Seven immortal unsleeping one-eyed sorcerers
stand upon the seven peaks that surround the Valley of the
Cave, each ready to hurl magical destruction on any who
venture near. The stream that flows from the valley teems
with invisible piranhas who eat only man-flesh, and is so
cold that if a single drop should touch your skin you would
instantly freeze to superconducting temperatures.

Or to put it another way, "There are some things Man
was not Meant To Know."

--
Er*********@sun.com

Nov 14 '05 #8
>
Thanks for everyone who answered my question. To answer Mike's
question:

I don't really have the "need" to do that yet but I am wondering how
does 'free' know how many bytes to free?
It knows. It doesn't have to tell you HOW it knows, it just does.
For example:

char* s = malloc(10);
free(s); // how many bytes to free?

How does free know how many bytes to free? I have heard that malloc
also allocate additional memory to hold some header information. Where
is this header information stored? If we have access to the header, we
can find that out?


The information might be stored in a large SQL database in a
sub-dungeon of Microsoft Corporation, where you will be taxed on
the memory you use (and more on the memory you don't give back).
The ANSI C standard doesn't say HOW, it just says to DO IT.

There are various trade-offs of speed vs. memory utilization
efficiency (aka fragmentation). For example, some implementations
add a little overhead, then round the result up to the next power
of two, so if you ask for a block of 4096, you might end up using
8192. Some implementations keep a linked list of free and allocated
memory, using various unportable mechanisms such as using the
low-order bit of a pointer to indicate whether the block is free
or not. Linked lists can get VERY slow if you allocate lots of
really tiny strings.

The information might be kept in a table somewhere, not at the
beginning and/or end of the allocated memory block.

Gordon L. Burditt
Nov 14 '05 #9
In article <db**************************@posting.google.com >,
pembed2003 <pe********@yahoo.com> wrote:

SNIP...
I don't really have the "need" to do that yet but I am wondering how
does 'free' know how many bytes to free? For example:

char* s = malloc(10);
free(s); // how many bytes to free?

How does free know how many bytes to free? I have heard that malloc
also allocate additional memory to hold some header information. Where
is this header information stored? If we have access to the header, we
can find that out?

Thanks!


The answer to that question depends on the implementation of the malloc(),
realloc(), et. all package. Two common implementations are:

1. Have malloc allocate slightly more data than requested and place the
length at the front of the memory block. The pointer that malloc
returns is to the byte just following the length. This method has the
advantage of being very simple to do. However in a virtual memory
system, it frequently requires a page in request in order for free()
to determine the size of the memory block just freed. A rather silly
thing to do if you're not going to modify or otherwise use the page
of memory just read in.

2. Have a "index" page of memory with page addresses and allocation sizes
for those pages. Keep track of which section are allocated using a
bit array on the index page. For example, FreeBSD gets memory in 4K byte
pages. Each page is then used for only allocations of a specified size.
You may have a page that is allocated 16 bytes at a time and used for
any memory request less than or equal to 16 bytes. Another page is
used 32 bytes at a time and handles requests for 17 to 32 bytes. This
pattern continues for 64, 128, 256, ... 4096 bytes. For requests over
4096 bytes, several pages are chained together. When freeing a chunk
of allocated memory, the index page simply needs to have a bit set or
reset so if the allocated memory is paged out, it doesn't need to be
paged back in. Since the index page is frequently accessed, it typically
remains active and isn't paged out.

I am certain that you can think of many more methods of keeping track of
allocated memory. I am also certain that attempting to use internal
implementation information about malloc() and company is the wrong thing to
do and is likely to change from system to system.
Nov 14 '05 #10
On 24 Jun 2004 10:08:28 -0700, pe********@yahoo.com (pembed2003)
wrote:
I don't really have the "need" to do that yet but I am wondering how
does 'free' know how many bytes to free? For example:

char* s = malloc(10);
free(s); // how many bytes to free?
It's a secret ;-) The implementation knows, but you don't, unless
you're writing the implementation. What's more, you don't want to know
- acting on such knowledge can only get you in trouble.
How does free know how many bytes to free? I have heard that malloc
also allocate additional memory to hold some header information. Where
is this header information stored? If we have access to the header, we
can find that out?

Not portably. The header is quite likely to be different from compiler
to compiler, platform to platform and version to version. If you use
such knowledge even for a particular program on a particular
implementation on a particular machine, it may break if you upgrade
the compiler or the operating system (since runtime libraries may be
shipped with the OS.)

--
Al Balmer
Balmer Consulting
re************************@att.net
Nov 14 '05 #11

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

Similar topics

6
by: grunes | last post by:
I wish to fread a few thousand bytes at a time in turn from several very large files from a DVD data disk, under Redhat Fedora Linux. When this is done the DVD drive wastes a lot of time and...
54
by: Neo | last post by:
Hi Folks, I've a simple qestion related to dynamic memory allocation in C here is the code: #include <stdio.h> int main() {
40
by: madireddy | last post by:
Hi, Inside a program how do i find out what size has been allocated to pointer using malloc. eg... int *p; p=(int*)malloc(1024*sizeof(int)); now how do find how much has been allocated to p?...
6
by: Laurent | last post by:
Hello, This is probably a dumb question, but I just would like to understand how the C# compiler computes the size of the managed structure or classes. I'm working on this class: public...
111
by: Tonio Cartonio | last post by:
I have to read characters from stdin and save them in a string. The problem is that I don't know how much characters will be read. Francesco -- ------------------------------------- ...
43
by: Frodo Baggins | last post by:
Hi all, We are using strcpy to copy strings in our app. This gave us problems when the destination buffer is not large enough. As a workaround, we wanted to replace calls to strcpy with strncpy....
4
by: Kenneth Brody | last post by:
I looked at my copy of n1124, and I didn't see anything about this particular situation... What happens if you realloc() to a size of zero? Implementations are allowed to return NULL on...
5
by: Paul | last post by:
hi, there, I was asked such a question: how to determine the size of memory of the int pointer pointed? for example int GetTheSizeofMemory(int *buffer) { int size; //enter your code here,...
36
by: James Harris | last post by:
Initial issue: read in an arbitrary-length piece of text. Perceived issue: handle variable-length data The code below is a suggestion for implementing a variable length buffer that could be used...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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...
1
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...
0
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,...
1
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...
0
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...
0
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...
0
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 ...

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.