473,545 Members | 2,042 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A malloc question

What happens to the pointer below?

SomeStruct *p;
p = malloc(100*size of(SomeStruct)) ; /* without a cast */
return((void *)(p+1)); /* will the returned pointer point
to the 2nd struct? */

Seems to me there is no guarantee it will.

/Why Tea

Dec 28 '06 #1
40 2527
Why Tea a écrit :
What happens to the pointer below?

SomeStruct *p;
p = malloc(100*size of(SomeStruct)) ; /* without a cast */
return((void *)(p+1)); /* will the returned pointer point
to the 2nd struct? */

Seems to me there is no guarantee it will.

/Why Tea
In my opinion it must point to p+1. Since p is a pointer
to SomeStruct, p+1 points to the second structure
in the table.

Dec 28 '06 #2
Why Tea wrote:
What happens to the pointer below?
SomeStruct *p;
p = malloc(100*size of(SomeStruct)) ; /* without a cast */
return((void *)(p+1)); /* will the returned pointer point
to the 2nd struct? */
Seems to me there is no guarantee it will.
Hello there,

The pointer arithmatic works according to the `type' of the pointer
`p'
that is `SomeStruct'.
So, the returned pointer should point to the 2'nd struct in the
dynamically
allocated array.

---
Regards
-PJP
http://www.cdacbangalore.in/~prasad

Dec 28 '06 #3


On Thu, 28 Dec 2006, jacob navia wrote:
Why Tea a écrit :
>What happens to the pointer below?

SomeStruct *p;
p = malloc(100*size of(SomeStruct)) ; /* without a cast */
return((void *)(p+1)); /* will the returned pointer point
to the 2nd struct? */

Seems to me there is no guarantee it will.

/Why Tea

In my opinion it must point to p+1. Since p is a pointer
to SomeStruct, p+1 points to the second structure
in the table.
Assuming of course that a valid declaration of malloc() is in scope (e.g.
via #include <stdlib.h>), and the memory allocation succeeded. Otherwise,
the behavior is undefined.

Emil
Dec 28 '06 #4

Why Tea wrote:
What happens to the pointer below?

SomeStruct *p;
p = malloc(100*size of(SomeStruct)) ; /* without a cast */
return((void *)(p+1)); /* will the returned pointer point
to the 2nd struct? */

Seems to me there is no guarantee it will.
Yes, there is no guarantee. You did not check if your allocation is
successful or not before returning the pointer.

Dec 28 '06 #5
Why Tea said:
What happens to the pointer below?

SomeStruct *p;
p = malloc(100*size of(SomeStruct)) ; /* without a cast */
return((void *)(p+1)); /* will the returned pointer point
to the 2nd struct? */

Seems to me there is no guarantee it will.
Provided you have a prototype in scope for malloc (i.e. you have included
<stdlib.h>), and provided malloc did not return NULL (which you do not
check), the returned pointer will indeed point to space properly aligned
for the SomeStruct type, at an offset of sizeof(SomeStru ct) from the
beginning of the allocated block. This is guaranteed by the Standard
(subject to the caveats I mentioned).

It is never necessary or desirable to cast the value returned by malloc
(unless your name is P J Plauger, which, in your case, presumably it
isn't).

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Dec 28 '06 #6
It is never necessary or desirable to cast the value returned by malloc
(unless your name is P J Plauger, which, in your case, presumably it
isn't).
Thanks for the answer. No, I', not P J :), so no cast for me...

One more question while I'm at it about the memory stuff. Assuming I
have the following code:

SomeStruct *p;
p = malloc(100 + sizeof(SomeStru ct)); /* 100 is not multiples of
sizeof(SomeStru ct) */
/* do something before freeing it */
free(p);

Will the entire memory pointed to by p be released? Does free(p) always
releases multiples of the data structure p points to?

Dec 28 '06 #7
Why Tea said:

<snip>
One more question while I'm at it about the memory stuff. Assuming I
have the following code:

SomeStruct *p;
p = malloc(100 + sizeof(SomeStru ct)); /* 100 is not multiples of
sizeof(SomeStru ct) */
/* do something before freeing it */
free(p);

Will the entire memory pointed to by p be released? Does free(p) always
releases multiples of the data structure p points to?
malloc() doesn't allocate data structures. It simply allocates a block of
memory, n bytes in size (where you supply n), and returns a pointer to the
start of that block. In this case, you calculate n like this: 100 +
sizeof(SomeStru ct). But malloc doesn't see that calculation. It only sees
the result. It doesn't know about SomeStruct, let alone sizeof(SomeStru ct).
It only sees 123, or 145, or whatever it is that 100+sizeof(Some Struct)
evaluates to. It will try to allocate that much memory, and return a
pointer to that memory if successful.

When you pass that pointer value to free(), the whole block is freed, and
the pointer value becomes indeterminate.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Dec 28 '06 #8
In article <11************ **********@42g2 000cwt.googlegr oups.com>,
Why Tea <yt****@gmail.c omwrote:
p = malloc(100 + sizeof(SomeStru ct)); /* 100 is not multiples of sizeof(SomeStru ct) */
/* do something before freeing it */
Be sure you know what you're doing here. You can't, for example,
reliably store 100 chars followed by a struct in this memory, because
the alignment of p+100 may not be suitable for the struct.

-- Richard

--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Dec 28 '06 #9

Richard Tobin wrote:
In article <11************ **********@42g2 000cwt.googlegr oups.com>,
Why Tea <yt****@gmail.c omwrote:
p = malloc(100 + sizeof(SomeStru ct)); /* 100 is not multiples of sizeof(SomeStru ct) */
/* do something before freeing it */

Be sure you know what you're doing here. You can't, for example,
reliably store 100 chars followed by a struct in this memory, because
the alignment of p+100 may not be suitable for the struct.
Thanks Richard. In fact I was reading someone else's code. The
intention of the code is to have a memory allocation similar to this:

|<- SomeStruct ->|<- UserStruct ->

Hence,
SomeStruct *p;
p = malloc(sizeof(S omeStruct) + sizeof(UserStru ct)); /* UserStruct can
be anything */
...
free(p);

(p+1) points to the beginning of UserStruct, so users can store
anything in there.

My understanding is, the paddings (if any) for memory alignment are
included in the calculation of sizeof(). So the code should work
properly. Is my understanding correct?

Dec 28 '06 #10

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

Similar topics

231
22974
by: Brian Blais | last post by:
Hello, I saw on a couple of recent posts people saying that casting the return value of malloc is bad, like: d=(double *) malloc(50*sizeof(double)); why is this bad? I had always thought (perhaps mistakenly) that the purpose of a void pointer was to cast into a legitimate date type. Is this wrong? Why, and what is considered to be...
66
3192
by: Knady | last post by:
Hi, I have the following problem, I must to do my assignment, but I really do not know how to use the malloc. I need create a program that will be used to do some algebrical computation on the matrix. How I can create dynamical the matrices with the name in order to be able to recall them. Thx
36
2238
by: Martin Andert | last post by:
Hello, I have a question regarding malloc and free. Here my code sample: int main() { /* allocating dynamic memory for array */ int* array = (int*) malloc(5 * sizeof(int)); /* ... program code ... */
23
6182
by: puzzlecracker | last post by:
Why is "new" a C++ language-level construct while "malloc" is a library function?
8
2540
by: Snis Pilbor | last post by:
First, let me announce that this is very possibly off-topic because malloc is a specific third party accessory to c, etc. I spent about an hour trying to find a more appropriate newsgroup and failed. If anyone could point one out, I would be much obliged. I'm using MSVC .NET, but the only .NET specific newsgroups I could find were vbasic...
12
3262
by: gooch | last post by:
I originally posted the following code in a group discussing threads but after further research I think I have a c question about the code. I know there are a couple of non standard c includes here and the POSIX stuff is non standard but this is how I stumbled onto this question. #include <INTEGRITY.h> #include <stdlib.h> #include...
25
2223
by: Why Tea | last post by:
Thanks to those who have answered my original question. I thought I understood the answer and set out to write some code to prove my understanding. The code was written without any error checking. --- #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct {
24
3106
by: VijaKhara | last post by:
hi all, i am trying to create a dynamic 2D array with size N x 3 (N will be put in as a parameter) using the following code: int **xyz; int i,N; N=30000; xyz=malloc(3*sizeof(int*));
17
1695
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...
71
19040
by: desktop | last post by:
I have read in Bjarne Stroustrup that using malloc and free should be avoided in C++ because they deal with uninitialized memory and one should instead use new and delete. But why is that a problem? I cannot see why using malloc instead of new does not give the same result.
0
7478
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...
0
7923
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...
0
7773
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...
1
5343
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...
0
4960
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...
0
3466
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...
1
1901
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
1
1025
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
722
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...

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.