473,777 Members | 1,715 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

malloc realloc and pointers

Hi all,

I m relatively new to C. I have few queries related to malloc():

1. When we perform malloc(), the memory allocated dynamically comes from
the heap area of the process in concern. Well, we then say that the heap
has shrinked. my query is: Is it that the heap physically does not
shrink but the perticular nodes are marked 'ALLOCATED' and for
subsequent calls to malloc() the memory manager remembers them and does
not reference them?

2. With realloc(), if some pointer 'ptr' is pointing initially to a
perticular position in a buffer (char *buffer) then on performing a
realloc() on this buffer, what will be 'ptr' pointing to?

3. whats the maximum memory size that we can allocate dynamically by
calling malloc() ?

4. Is it valid in C to typecast a pointer? eg. code snippet... of
course int is 16 bit and long is 32 bit.
int *variable, value;
*((long*)variab le)++ = value;
*((long*)variab le)++ = value;
*((long*)variab le)++ = value;
*((long*)variab le)++ = value;

thanx in advance

Nov 29 '07 #1
22 1981
ravi <nos...@nospam. invalidwrote:
Hi all,

I m relatively new to C.
Then why ask questions on how it's implemented? You're
trying to run before you can crawl.
I have few queries related to malloc():

1. When we perform malloc(), the memory allocated
dynamically comes from the heap area of the process in
concern.
If you say so. The language standard does not specify how
malloc is implemented, merely how it must operate.
Well, we then say that the heap has shrinked. my query
is: Is it that the heap physically does not shrink but
the perticular nodes are marked 'ALLOCATED' and for
subsequent calls to malloc() the memory manager
remembers them and does not reference them?
You should ask in a group where such implementation details
are topical.
2. With realloc(), if some pointer 'ptr' is pointing
initially to a perticular position in a buffer (char
*buffer) then on performing a realloc() on this buffer,
what will be 'ptr' pointing to?
The original pointer value becomes indeterminate if the
allocation is successful.
3. whats the maximum memory size that we can allocate
dynamically by calling malloc() ?
The most you can try for is ((size_t) -1). The most you
can actually allocate depends on the implementation.
4. Is it valid in C to typecast a pointer?
Yes, but subject to a few rules. Converting between
different non-void types isn't as well defined as
some program code would have you believe.
eg. code snippet... of
course int is 16 bit and long is 32 bit.
If that has any relevance, then you're heading down the
wrong path in your quest to learn C.
int *variable, value;
*((long*)variab le)++ = value;
This potentially breaks several rules on pointer conversion.
It also violates a constraint.

The cast from int * to long * is not required to be well
defined. Even if it is, it will not produce a modifiable
lvalue suitable for postfix ++.

--
Peter
Nov 29 '07 #2
ravi wrote:
>
Hi all,

I m relatively new to C. I have few queries related to malloc():

1. When we perform malloc(), the memory allocated dynamically comes from
the heap area of the process in concern.
Technically, C doesn't define "heap". However, it is a term in
general use to mean "the memory from which malloc and friends
get their memory".
Well, we then say that the heap
has shrinked.
Not necessarily. Perhaps the amount of memory available on the
heap has shrunk, but even that's not necessarily true. It is
possible that the memory you request wasn't available in the
existing heap, and so the heap was grown to accomodate your
request. It is possible that the result is that you now have
more memory available on the heap than before the call to
malloc().
my query is: Is it that the heap physically does not
shrink but the perticular nodes are marked 'ALLOCATED' and for
subsequent calls to malloc() the memory manager remembers them and does
not reference them?
The memory management within malloc/calloc/etc. keeps track of
what memory is used and that is still available. The details on
How it does this is entirely up to the implemenation.
2. With realloc(), if some pointer 'ptr' is pointing initially to a
perticular position in a buffer (char *buffer) then on performing a
realloc() on this buffer, what will be 'ptr' pointing to?
Three possibilities:

1) realloc() returns the same pointer, in which case ptr is still
valid, pointing to the newly-sized buffer.

2) realloc() returns a different pointer, in which case ptr is
no longer valid, and must not be dereferenced.

3) realloc() returns NULL, in which case ptr is pointing to the
unchanged memory region as before.

Typically, the only use for the old pointer is to remember where
it pointed to when realloc() returns NULL. Otherwise, simply use
the new pointer.
3. whats the maximum memory size that we can allocate dynamically by
calling malloc() ?
Whatever is the maximum value of a size_t variable, though you
are more likely to run into limits of the platform you are running
on. (For example, size_t may allow values up to 4GB-1, but the
O/S may only allow 2GB.)
4. Is it valid in C to typecast a pointer? eg. code snippet... of
course int is 16 bit and long is 32 bit.
int *variable, value;
*((long*)variab le)++ = value;
*((long*)variab le)++ = value;
*((long*)variab le)++ = value;
*((long*)variab le)++ = value;
If variable is properly aligned, I believe it's valid.

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer .h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>

Nov 29 '07 #3
In article <47************ ***@spamcop.net >,
Kenneth Brody <ke******@spamc op.netwrote:
>ravi wrote:
>int *variable, value;
*((long*)varia ble)++ = value;
*((long*)varia ble)++ = value;
*((long*)varia ble)++ = value;
*((long*)varia ble)++ = value;
>If variable is properly aligned, I believe it's valid.
variable has not been initialized, so it is a dangling pointer.
--
"Beware of bugs in the above code; I have only proved it correct,
not tried it." -- Donald Knuth
Nov 29 '07 #4
On Thu, 29 Nov 2007 17:00:05 -0500, Kenneth Brody wrote:
ravi wrote:
>2. With realloc(), if some pointer 'ptr' is pointing initially to a
perticular position in a buffer (char *buffer) then on performing a
realloc() on this buffer, what will be 'ptr' pointing to?

Three possibilities:

1) realloc() returns the same pointer, in which case ptr is still
valid, pointing to the newly-sized buffer.
According to DR #260, applied to realloc, even if memcmp proves the new
pointer is identical to the old pointer, you're not allowed to use them
interchangeably . If you pass a non-null pointer ptr to realloc, and it
doesn't return a null pointer, ptr is no longer valid.

(I do not believe the DR's conclusions can be drawn from any
interpretation of the actual standard, and in fact I believe some points
from the DR directly contradict explicit guarantees by the standard, but
that's just me.)
Nov 29 '07 #5
ravi wrote:
>
I m relatively new to C. I have few queries related to malloc():

1. When we perform malloc(), the memory allocated dynamically
comes from the heap area of the process in concern. Well, we then
say that the heap has shrinked. my query is: Is it that the heap
physically does not shrink but the perticular nodes are marked
'ALLOCATED' and for subsequent calls to malloc() the memory
manager remembers them and does not reference them?
There is not necessarily anything called a heap. That is an
implementors decision. Somehow or other the implementor guarantees
that subsequent malloc calls do not return pointers to previously
allocated space (unless freed).
2. With realloc(), if some pointer 'ptr' is pointing initially to a
perticular position in a buffer (char *buffer) then on performing a
realloc() on this buffer, what will be 'ptr' pointing to?
That depends. If realloc succeeds, it returns a replacement value
for ptr, which has the desired space and preserves the original
data. If realloc fails it return NULL, and ptr and *ptr are both
unaltered.
3. whats the maximum memory size that we can allocate dynamically by
calling malloc() ?
Depends on the system. All you can find out is that a malloc
(etc.) request is fulfilled or rejected.
4. Is it valid in C to typecast a pointer? eg. code snippet... of
course int is 16 bit and long is 32 bit.
int *variable, value;
*((long*)variab le)++ = value;
*((long*)variab le)++ = value;
*((long*)variab le)++ = value;
*((long*)variab le)++ = value;
Very likely to cause serious run-time faults. Don't do it.

--
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home .att.net>
Try the download section.

--
Posted via a free Usenet account from http://www.teranews.com

Nov 30 '07 #6
On Thu, 29 Nov 2007 21:50:38 +0100 (CET), ravi <no****@nospam. invalid>
wrote in comp.lang.c:
Hi all,

I m relatively new to C. I have few queries related to malloc():

1. When we perform malloc(), the memory allocated dynamically comes from
the heap area of the process in concern. Well, we then say that the heap
has shrinked. my query is: Is it that the heap physically does not
shrink but the perticular nodes are marked 'ALLOCATED' and for
subsequent calls to malloc() the memory manager remembers them and does
not reference them?

2. With realloc(), if some pointer 'ptr' is pointing initially to a
perticular position in a buffer (char *buffer) then on performing a
realloc() on this buffer, what will be 'ptr' pointing to?

3. whats the maximum memory size that we can allocate dynamically by
calling malloc() ?

4. Is it valid in C to typecast a pointer? eg. code snippet... of
course int is 16 bit and long is 32 bit.
int *variable, value;
*((long*)variab le)++ = value;
This is not legal C code. The cast generates an rvalue, and the post
increment operator cannot be applied to lvalues. You cannot assign to
the result of a cast.
*((long*)variab le)++ = value;
*((long*)variab le)++ = value;
*((long*)variab le)++ = value;

thanx in advance
--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
Nov 30 '07 #7
On Thu, 29 Nov 2007 17:00:05 -0500, Kenneth Brody wrote:
ravi wrote:
>2. With realloc(), if some pointer 'ptr' is pointing initially to a
perticular position in a buffer (char *buffer) then on performing a
realloc() on this buffer, what will be 'ptr' pointing to?

Three possibilities:

1) realloc() returns the same pointer, in which case ptr is still
valid, pointing to the newly-sized buffer.

2) realloc() returns a different pointer, in which case ptr is
no longer valid, and must not be dereferenced.

3) realloc() returns NULL, in which case ptr is pointing to the
unchanged memory region as before.
What happens when ptr is not one returned by a previous
invocation to malloc(), calloc() or realloc()?

Nov 30 '07 #8

"K. Jennings" <kj*******@resu rgence.netwrote in message
news:pa******** *************@r esurgence.net.. .
On Thu, 29 Nov 2007 17:00:05 -0500, Kenneth Brody wrote:
>ravi wrote:
>>2. With realloc(), if some pointer 'ptr' is pointing initially to a
perticular position in a buffer (char *buffer) then on performing a
realloc() on this buffer, what will be 'ptr' pointing to?

Three possibilities:

1) realloc() returns the same pointer, in which case ptr is still
valid, pointing to the newly-sized buffer.

2) realloc() returns a different pointer, in which case ptr is
no longer valid, and must not be dereferenced.

3) realloc() returns NULL, in which case ptr is pointing to the
unchanged memory region as before.

What happens when ptr is not one returned by a previous
invocation to malloc(), calloc() or realloc()?
then, if you are the program, ninjas run up, kick you somewhere painful, and
insert a corncob somewhere painful.
one then has to try to hobble off to the bathroom for a 'core dump'...

Nov 30 '07 #9
"K. Jennings" wrote:
>
.... snip ...
>>
3) realloc() returns NULL, in which case ptr is pointing to the
unchanged memory region as before.

What happens when ptr is not one returned by a previous
invocation to malloc(), calloc() or realloc()?
Then you know that realloc moved the storage. It doesn't affect
the data held by the pointed to object.

--
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home .att.net>
Try the download section.

--
Posted via a free Usenet account from http://www.teranews.com

Nov 30 '07 #10

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

Similar topics

9
4031
by: WL | last post by:
Hey, all. I'm creating an array of strings (char **argv style) on the fly, and using realloc to create string pointers, and malloc for the strings itself (if that makes any sense). I'm using the construct ptr = realloc(ptr, size); *ptr = malloc(string_length); strncpy(ptr, src, string_length); to call realloc() multiple times. This should be ok, right?
10
9041
by: Ian Todd | last post by:
Hi, I am trying to read in a list of data from a file. Each line has a string in its first column. This is what i want to read. I could start by saying char to read in 1000 lines to the array( i think!!). But I want to use malloc. Each string is at most 50 characters long, and there may be zero to thousands of lines. How do I actually start the array? I have seen char **array etc. At first I tried char *array but I think that gives 50...
7
2216
by: Rano | last post by:
/* Hello, I've got some troubles with a stupid program... In fact, I just start with the C language and sometime I don't understand how I really have to use malloc. I've readden the FAQ http://www.eskimo.com/~scs/C-faq/faq.html but it doesn't seem to answer my questions... So, I've made an example behind, with some included questions...
50
2869
by: Joseph Casey | last post by:
Greetings. I have read that the mistake of calling free(some_ptr) twice on malloc(some_data) can cause program malfunction. Why is this? With thanks. Joseph Casey.
27
1939
by: ncf | last post by:
Hi all. In another topic, I was informed that I had to dynamically allocate memory instead of just trying to expand on a list. (I'm trying to learn C, and have a strong background in PHP and Python) In light of that, I have been trying to learn malloc, realloc, and free, but to no avail. But for some reason, I'm getting segfaults right and left, and to be honest, I am not having any luck at all really in finding out why it isn't...
21
470
by: ramu | last post by:
Hi, Will the memory allocated by malloc and realloc be contiguous? regards
82
31156
by: quiberon2 | last post by:
Hi, Sorry if it might be a stupid question but what should returns malloc(0) ? void *ptr = malloc(0); I am running gcc 3.3.5 and a non-null address is returned. ( in the compiler that I am currently implementing, NULL is returned. Is it wrong ?)
17
1722
by: Christopher Benson-Manica | last post by:
Some recent posts got me thinking about how one might have dealt with simplistic malloc() implementations which might return NULL for a 64K request but might accept two 32K requests or four 16K requests. (I'm assuming, perhaps incorrectly, that quality modern implementations will coalesce free space as necessary and if possible to satisfy requests.) I came up with the following (compilable but untested) first cut at code to try a...
35
5687
by: Bill Cunningham | last post by:
My string.h headers declares two functions I have been using called memfrob and strfry. They are encryption types functions. My man pages say they are standard to linux c and gnu c. They sure aren't in my C books. Interesting functions by they're OT here but this raises to me a question. If a function returns a pointer to a void and and as it's first parameter a pointer to a void. Then should that function's first parameter accept a string...
0
9628
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
9464
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
10292
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
9923
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
8954
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
6722
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
5368
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5497
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2860
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.