473,289 Members | 1,963 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,289 software developers and data experts.

malloc question again

In the following code:

char *p;

while(1){

p = malloc(10*sizeof(*p));

//Do something with p

}

The while( ) loop keeps allocate memory to p. What will happen?

Should I do as below?

char *p;

while(1){

p = malloc(10*sizeof(*p));

//Do something with p

free(p);
}

Thanks a lot.

Jun 2 '06 #1
6 1933


Jack wrote On 06/02/06 12:54,:
In the following code:

char *p;

while(1){

p = malloc(10*sizeof(*p));

//Do something with p

}

The while( ) loop keeps allocate memory to p. What will happen?
Each iteration of the loop will call malloc() and
request another ten bytes. Unless the "do something"
code free()s some of the allocated memory, malloc()
will eventually exhaust all the available memory and
return NULL to indicate that it couldn't honor the
request.
Should I do as below?

char *p;

while(1){

p = malloc(10*sizeof(*p));

//Do something with p

free(p);
}


That is one thing you could do. Another would be

p = malloc(10 * sizeof *p;
if (p == NULL) ...
while (1) {
//Do something with p
}
free (p); // assume a `break'

Still another might be to put the p values into a data
structure of some kind -- linked list, tree, whatever --
that will "remember" the values so you can access the
allocated memory later.

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

Jun 2 '06 #2

Jack wrote:
In the following code:

char *p;

while(1){

p = malloc(10*sizeof(*p));

//Do something with p

}

The while( ) loop keeps allocate memory to p. What will happen?
Depends on the operating system. malloc() may start returning NULL
from some point onwards , or your programme will crash or terminated
by the operating system and it's even possible that the operating
system
will get confused and terminate other programmes. I have heard the last
possibility happening in Linux.

Should I do as below?

char *p;

while(1){

p = malloc(10*sizeof(*p));

//Do something with p

free(p);
}


Yes , you can do that. Of course if you know in advance that you're
going
to need space for 10 char's you don't need to use malloc() at all ;
just declare
an array of size 10.

Jun 2 '06 #3

Eric Sosman wrote:
Jack wrote On 06/02/06 12:54,:
In the following code:

char *p;

while(1){

p = malloc(10*sizeof(*p));

//Do something with p

}

The while( ) loop keeps allocate memory to p. What will happen?
Each iteration of the loop will call malloc() and
request another ten bytes. Unless the "do something"
code free()s some of the allocated memory, malloc()
will eventually exhaust all the available memory and
return NULL to indicate that it couldn't honor the
request.


Assume that 5 blocks of ten bytes memory are allocated, which one does
p points to?
the last one?
Should I do as below?

char *p;

while(1){

p = malloc(10*sizeof(*p));

//Do something with p

free(p);
}


That is one thing you could do. Another would be

p = malloc(10 * sizeof *p;
if (p == NULL) ...
while (1) {
//Do something with p
}
free (p); // assume a `break'

Still another might be to put the p values into a data
structure of some kind -- linked list, tree, whatever --
that will "remember" the values so you can access the
allocated memory later.


If each time I have to allocate a different size of memory to p, such
as:

p = malloc(N * sizeof(*p)); //N is a variable

then I have to put the malloc into the while loop, right?

Thanks.

Jack

Jun 2 '06 #4
Jack schrieb:
Eric Sosman wrote:
Jack wrote On 06/02/06 12:54,:
In the following code:

char *p;

while(1){

p = malloc(10*sizeof(*p));

//Do something with p

}

The while( ) loop keeps allocate memory to p. What will happen?


Each iteration of the loop will call malloc() and
request another ten bytes. Unless the "do something"
code free()s some of the allocated memory, malloc()
will eventually exhaust all the available memory and
return NULL to indicate that it couldn't honor the
request.


Assume that 5 blocks of ten bytes memory are allocated, which one does
p points to?
the last one?


Please be precise in your questions -- I am not sure whether you
are asking for the value of p or the relative position of allocated
storage...

p at "// Do something ..." obviously either is a null pointer
(perfectly possible) or points to at least 10 bytes of
allocated storage.
As long as p does not become a null pointer, p points to the storage
returned by the latest call to malloc().
Should I do as below?

char *p;

while(1){

p = malloc(10*sizeof(*p));

//Do something with p

free(p);
}


That is one thing you could do. Another would be

p = malloc(10 * sizeof *p;
if (p == NULL) ...
while (1) {
//Do something with p
}
free (p); // assume a `break'

Still another might be to put the p values into a data
structure of some kind -- linked list, tree, whatever --
that will "remember" the values so you can access the
allocated memory later.


If each time I have to allocate a different size of memory to p, such
as:

p = malloc(N * sizeof(*p)); //N is a variable

then I have to put the malloc into the while loop, right?


Not necessarily.
It may suffice to know the value range N can have during a
run of the programme and allocate sufficiently much storage
before the loop.
Or have an array of the respective size.
Another thing would be to have
size_t size = 0;
char *p = NULL;
p = malloc(INIT_SIZE * sizeof *p);
if (p == NULL) {
/* Your error handling here */
}
size = INIT_SIZE;

while (1) {
....
if (N > size) {
char *temp = realloc(p, N);
if (temp == NULL) {
/* Your error handling here; p is still valid */
}
p = temp;
size = N;
}
....
free(p);

If you explain what exactly you have in mind, we may be able
to help you better.
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Jun 2 '06 #5
uhhh yes...

if you reset your pointer to a different area of memory you are
creating the definition of a memory leak...

Jack wrote:
In the following code:

char *p;

while(1){

p = malloc(10*sizeof(*p));

//Do something with p

}

The while( ) loop keeps allocate memory to p. What will happen?

Should I do as below?

char *p;

while(1){

p = malloc(10*sizeof(*p));

//Do something with p

free(p);
}

Thanks a lot.


Jun 2 '06 #6
Jack posted:

The while( ) loop keeps allocate memory to p. What will happen?

Here's a dynamic allocation exhaustion test for you:
(Unchecked code, likely to contain an error or two:)
typedef struct MemAllocInfo {
struct MemAllocInfo *previous;
} MemAllocInfo;
#include <stdlib.h>

int main(void)
{
MemAllocInfo info = {0};

MemAllocInfo *p_info = &info;

for (;;)
{
MemAllocInfo *tempptr = malloc( sizeof(*tempptr) );

if (!tempptr) break;

tempptr->previous = p_info;

p_info = tempptr;
}
do
{
MemAllocInfo *tempptr = p_info.previous;

free(p_info);

p_info = tempptr;
}
while( p_info );
}
(That code my call "free" on the stack-allocated object...)
-Tomás
Jun 3 '06 #7

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

Similar topics

7
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...
7
by: Fatted | last post by:
I'm trying to learn how to create arrays dynamically. But its just not happening. Have a look at code below and point and laugh where appropriate... First part of program, I'm using an array of...
1
by: Dawn Minnis | last post by:
Hey guys - this code when called with parameters: driver.o n n 12 12 12 12 12 12 2.6 3.2 is kicking back a segmentation fault. I've read the rest of the postings but am still confused. Can...
24
by: Hrv'uljak | last post by:
Anybody has a better solution? How to avoid memory allocation in main function? Thanks! -------- #include <stdio.h> #include <conio.h> #include <string.h> #include <malloc.h>
68
by: James Dow Allen | last post by:
The gcc compiler treats malloc() specially! I have no particular question, but it might be fun to hear from anyone who knows about gcc's special behavior. Some may find this post interesting;...
71
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...
22
by: ravi | last post by:
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,...
173
by: Marty James | last post by:
Howdy, I was reflecting recently on malloc. Obviously, for tiny allocations like 20 bytes to strcpy a filename or something, there's no point putting in a check on the return value of malloc....
6
by: Peter Michaux | last post by:
Suppose I have implemented a language with garbage collection in C. I have wrapped malloc in my own C function. If malloc returns NULL then I can run the garbage collector and then try malloc...
25
by: jbholman | last post by:
I am pretty new to C and doing my first project in C. I actually read almost the entire FAQ, but can't seem to figure out this problem. I have a structure. I have a list of these structures. ...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...

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.