473,757 Members | 2,284 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Does C guarantee the data layout of the memory allocated by malloc function?

Hello experts,
1. Does C guarantee the data layout of the memory allocated by malloc
function on the heap. I mean, for example, if I allocate a array of 100
elements of structure, can I always reference a correct/valid structure
member upon that allocated memory?

If I allocate memory, for example like this way:

lp_Person = (person_t *)malloc(CNT * sizeof(person_t ));

I guess the malloc/compiler doesn't know the detail of the data type
person_t. It only know the size of the object of the data type. So, how
can I use the members of the object of person_t (suppose it had
members) without compiler knowing it.

2. Is the base type of a pointer very important? I ever read one book,
it says "A pointer is not just a pointer, but a pointer with some
particular data type" (perhaps like this). Is it right?

3. If I allocate memory inside a function named f1(), is it better for
me to delay the de-allocation of that memory in some other functions
later?
Could you please also give me some more suggestion on my following
code, thank you very much.
lovecreatesbeau ty
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#define NMLEN 30

typedef enum {
male = 1,
female = 2
} gender_t;

typedef struct {
char name[NMLEN];
gender_t gender;
int age;
} person_t;

typedef enum {
false = 0,
true = 1
} bool_t;
int NameListInitial ization(void){
const int CNT = 100;
int ln_LoopCnt = 0;
person_t * lp_Person = NULL;
char la_PersonName[NMLEN] = {'\0'};
bool_t lb_IsAllocated = false;
lp_Person = (person_t *)malloc(CNT * sizeof(person_t ));
if (lp_Person != NULL){
lb_IsAllocated = true;

for (ln_LoopCnt = 0; ln_LoopCnt < CNT ; ++ln_LoopCnt){
memset(la_Perso nName, 0x00, sizeof(la_Perso nName));
memset(lp_Perso n[ln_LoopCnt].name,
0x00,
sizeof(lp_Perso n[ln_LoopCnt].name));

itoa(ln_LoopCnt , la_PersonName, 10);
strcat(la_Perso nName, "-Anonymous");
strcpy(lp_Perso n[ln_LoopCnt].name, la_PersonName);
lp_Person[ln_LoopCnt].gender = (gender_t)(
ln_LoopCnt % 2 + 1);
lp_Person[ln_LoopCnt].age = ln_LoopCnt;
}
}

/* do something here ... */

if (lb_IsAllocated == true){
free(lp_Person) ; /* Can I call this free in other place? */
}

return 0;
}

Nov 15 '05 #1
6 2315
>1. Does C guarantee the data layout of the memory allocated by malloc
function on the heap. I mean, for example, if I allocate a array of 100
elements of structure, can I always reference a correct/valid structure
member upon that allocated memory?
What does reference ... upon mean? Is that some kind of kinky byte sex?

The memory allocated by malloc() is guaranteed to be contiguous
within itself, otherwise there would be no way to find it with just
the pointer returned by malloc(). The memory allocated in one call
to malloc() is not guaranteed to be contiguous with the memory in
any other call to malloc() (and in one implementation I'm familiar
with, no two chunks of memory allocated by malloc() will EVER be
contiguous to each other).
If I allocate memory, for example like this way:

lp_Person = (person_t *)malloc(CNT * sizeof(person_t ));
Don't cast the return value of malloc().
I guess the malloc/compiler doesn't know the detail of the data type
person_t. It only know the size of the object of the data type. So, how
can I use the members of the object of person_t (suppose it had
members) without compiler knowing it.
Assuming a lp_Person is declared as a person_t *, the first
element is lp_Person[0], and the next one is lp_Person[1], ...
Then you can refer to things like lp_Person[0].hat_size .
2. Is the base type of a pointer very important? I ever read one book,
it says "A pointer is not just a pointer, but a pointer with some
particular data type" (perhaps like this). Is it right?
Yes. The difference in address between lp_Person[0] and lp_Person[1]
is the size of a person_t. The difference between ((char *)
lp_Person)[0] and ((char *) lp_Person)[1] is one byte.
3. If I allocate memory inside a function named f1(), is it better for
me to delay the de-allocation of that memory in some other functions
later?
Don't free the memory before you finish needing it.
Free the memory after you do finish needing it.
Could you please also give me some more suggestion on my following
code, thank you very much.
lovecreatesbea uty
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#define NMLEN 30

typedef enum {
male = 1,
female = 2
} gender_t;

typedef struct {
char name[NMLEN];
30 characters isn't nearly enough for real human names.
gender_t gender;
int age;
} person_t;

typedef enum {
false = 0,
true = 1
} bool_t;
int NameListInitial ization(void){
const int CNT = 100;
int ln_LoopCnt = 0;
person_t * lp_Person = NULL;
char la_PersonName[NMLEN] = {'\0'};
bool_t lb_IsAllocated = false;
lp_Person = (person_t *)malloc(CNT * sizeof(person_t ));
if (lp_Person != NULL){
lb_IsAllocated = true;

for (ln_LoopCnt = 0; ln_LoopCnt < CNT ; ++ln_LoopCnt){
memset(la_Perso nName, 0x00, sizeof(la_Perso nName));
memset(lp_Perso n[ln_LoopCnt].name,
0x00,
sizeof(lp_Perso n[ln_LoopCnt].name));

itoa(ln_LoopCnt , la_PersonName, 10); There is no function itoa() in standard C.
strcat(la_Perso nName, "-Anonymous");
strcpy(lp_Perso n[ln_LoopCnt].name, la_PersonName);
lp_Person[ln_LoopCnt].gender = (gender_t)(
ln_LoopCnt % 2 + 1);
lp_Person[ln_LoopCnt].age = ln_LoopCnt;
}
}

/* do something here ... */

if (lb_IsAllocated == true){
free(lp_Person) ; /* Can I call this free in other place? */ As written, lp_Person is about to be lost, so you CAN'T use its value
in another place. If, on the other hand, you returned lp_Person to
the function, it would be possible to free it in another place.
}

return 0;
}


Gordon L. Burditt
Nov 15 '05 #2
KJ
Friend when u allocate memory using malloc the bytes allocaed is
always contiguous. It returns the starting byte offset. Now questions
comes how do we manipulate the data stored in bytes. For example
int *p = (int*)malloc(10 *sizeof(int));

p will get the starting byte offset. where will p+1 refer to. Here
comes the type of pointer. Since the pointer p is of int type (assuming
sizeof(int) is 4) p+1 or p[1]refers to starting offset + 4bytes. so now
it points to the second int value of the allocation.

if u uset structure then increasing pointer of structure by one means
pointing to next structure values.

U can free the allocation anywhere but u must have the pointer pointing
to the starting offset of the allocation.

Nov 15 '05 #3
lovecreatesbeau ty wrote:
Hello experts,
1. Does C guarantee the data layout of the memory allocated by malloc
function on the heap. I mean, for example, if I allocate a array of 100
elements of structure, can I always reference a correct/valid structure
member upon that allocated memory?

If I allocate memory, for example like this way:

lp_Person = (person_t *)malloc(CNT * sizeof(person_t )); Don't cast the return value of malloc !
I guess the malloc/compiler doesn't know the detail of the data type
person_t. It only know the size of the object of the data type. So, how
can I use the members of the object of person_t (suppose it had
members) without compiler knowing it. malloc doesn't know, but it's required to give you memory aligned suitable
for any data type.

You can't access the members of a structure without the compiler knowing
about them.
2. Is the base type of a pointer very important? I ever read one book,
it says "A pointer is not just a pointer, but a pointer with some
particular data type" (perhaps like this). Is it right? Yes.
3. If I allocate memory inside a function named f1(), is it better for
me to delay the de-allocation of that memory in some other functions
later?

Deallocate when done with it, wherever that is.
Nov 15 '05 #4

Gordon Burditt wrote:
What does reference ... upon mean? Is that some kind of kinky byte sex?
Hi Gordon, thanks for your kindly help. Sorry for my poor English. I
mean that Whether I refer to the members of the object of the
particular data type in the allocated member?

When allocate with malloc(), it only knows the size but don't know the
layout of the object of that particular data type. I'm a little
confused on it.
Don't cast the return value of malloc().
Does it comply to the latest Language Standard?
Gordon L. Burditt


Best Regards

lovecreatesbeau ty

Nov 15 '05 #5
lovecreatesbeau ty wrote:
Gordon Burditt wrote:
What does reference ... upon mean? Is that some kind of kinky byte sex?

Hi Gordon, thanks for your kindly help. Sorry for my poor English. I
mean that Whether I refer to the members of the object of the
particular data type in the allocated member?

When allocate with malloc(), it only knows the size but don't know the
layout of the object of that particular data type. I'm a little
confused on it.


Sure, as Gordon mentions, your only guarantee then is that the memory
block for the size you requested is contiguous if malloc() was successful.

malloc() doesn't need to know about the layout of your memory. You
define that by the datatype pointer you assigned with malloc(). e.g.

struct mystruct {
int element1;
char element2;
} *pmystruct;

pmystruct = malloc(sizeof(m ystruct));

So, the type 'struct mystruct' defines the layout. You just need to make
sure that you allocate enough memory, and this is what the 'sizeof'
operator is used for.

Don't cast the return value of malloc().

Does it comply to the latest Language Standard?

Gordon L. Burditt

Best Regards

lovecreatesbeau ty

Nov 15 '05 #6
"lovecreatesbea uty" <lo************ ***@gmail.com> wrote:
# Hello experts,
#
#
# 1. Does C guarantee the data layout of the memory allocated by malloc
# function on the heap. I mean, for example, if I allocate a array of 100
# elements of structure, can I always reference a correct/valid structure
# member upon that allocated memory?
#
# If I allocate memory, for example like this way:
#
# lp_Person = (person_t *)malloc(CNT * sizeof(person_t ));

If you allocate N*sizeof(T) chars, you will have enough space for
at least N elements. If you save the pointer,
T *p=malloc(N*siz eof(T)), you can access successive elements as
p[0], p[1], p[2], ... , p[N-1]. Any alignment issues and filler space
are taken care for you.

# 2. Is the base type of a pointer very important? I ever read one book,
# it says "A pointer is not just a pointer, but a pointer with some
# particular data type" (perhaps like this). Is it right?

You can cast a function pointer to a function pointer and a data
pointer to a data pointer. All struct pointers are the same; for
other data pointers, the compiler is allowed to use different
representations .

malloc returns a (void*). If you assign or cast to (T*), the
compiler will insert any magic if it needs to change the pointer
value.

On some systems, a function pointer can be a code address and
a data address. That's why data and function pointers are different
beasts.

# 3. If I allocate memory inside a function named f1(), is it better for
# me to delay the de-allocation of that memory in some other functions
# later?

There is no 'better' or 'worse'. It is a matter of interface design.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
No pleasure, no rapture, no exquisite sin greater than central air.
Nov 15 '05 #7

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

Similar topics

4
3862
by: Thomas Paul Diffenbach | last post by:
Can anyone point me to an open source library of /statically allocated/ data structures? I'm writing some code that would benefit from trees, preferably self balancing, but on an embedded system that doesn't offer dynamic memory allocation (to be clear: no malloc, no realloc), and with rather tight memory constraints. Writing my own malloc to do dynamic allocation from some static pool isn't really an option, for various reasons, not...
20
3061
by: Jonas | last post by:
Hi, I'm 99 % sure that Standard C guarantees to do a memory move inside realloc() in case the new, returned memory block (address) is different than the original one. Can any C expert confirm this to me, please? Thanks, Jonas PS. I using C90, not C99--if it makes a difference.
24
3818
by: David Mathog | last post by:
If this: int i,sum; int *array; for(sum=0, i=0; i<len; i++){ sum += array; } is converted to this (never mind why for the moment):
74
4044
by: Suyog_Linux | last post by:
I wish to know how the free()function knows how much memory to be freed as we only give pointer to allocated memory as an argument to free(). Does system use an internal variable to store allocated memory when we use malloc(). Plz help......
5
307
by: RoSsIaCrIiLoIA | last post by:
why not to build a malloc_m() and a free_m() that *check* (if memory_debug=1) if 1) there are some errors in bounds of *all* allocated arrays from them (and trace-print the path of code that make the error and exit) just when malloc_m and free_m start. (I use a 1100 static array for write the path (like a queue) of called function, operator, etc and write using '+' where is find the memory error) 2) if the pointer to free is alredy...
31
3738
by: bilbothebagginsbab5 AT freenet DOT de | last post by:
Hello, hello. So. I've read what I could find on google(groups) for this, also the faq of comp.lang.c. But still I do not understand why there is not standard method to "(...) query the malloc package to find out how big an allocated block is". ( Question 7.27) Is there somwhere explained why - because it would seem to me, that free()
7
1471
by: grocery_stocker | last post by:
Given the following snippet of code: (taken from http://www.gnu.org/software/libc/manual/html_node/Malloc-Examples.html) void * xmalloc (size_t size) { register void *value = malloc (size); if (value == 0) fatal ("virtual memory exhausted");
48
5842
by: avasilev | last post by:
Hi all, my question is: if i allocate some memory with malloc() and later free it (using free()), is there a possibility that a consequent malloc() will allocate memort at the same starting address and will return the same pointer as the previous malloc(). I would like to have confirmation on whether this is practically a concern when pointers are used to uniquely identify data structure instances - like in this example:
89
6065
by: Cuthbert | last post by:
After compiling the source code with gcc v.4.1.1, I got a warning message: "/tmp/ccixzSIL.o: In function 'main';ex.c: (.text+0x9a): warning: the 'gets' function is dangerous and should not be used." Could anybody tell me why gets() function is dangerous?? Thank you very much. Cuthbert
0
9487
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
9297
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
10069
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
9735
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
8736
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
7285
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...
0
5324
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3828
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
3
3395
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.