473,425 Members | 1,798 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,425 software developers and data experts.

malloc experiments

This program compiles fine, but are there any hidden dangers
in it, or is it ok?

Experiment 1 ##################################################

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>

int main()
{
struct pres {
char name[25];
struct pres *next;
};

struct pres *president;

president = (struct pres *)malloc(sizeof(struct pres));

strcpy(president->name, "George Washington");
president->next = (struct pres *)malloc(sizeof(struct pres));

printf("The first structure has been created:\n");
printf("president->name = %s\n", president->name);
printf("next structure address = %i\n", president->next);

return 0;
}

################################################## #################

--Steve

Nov 13 '05
59 5096
Dave Vandervies wrote:
What return value? If you don't use it, then there isn't one.
Fine, then, the value it would have returned had you used it.


Great, now you are arguing my side of the question.
(I should know better than to get myself into this sort of thing by now.)

How about, don't make dopey statements? Your premise was ludicrous.


Brian Rodenborn
Nov 13 '05 #51
Ravi Uday wrote:

[ snip ]
int main(void)
{
int wrong_return_type_malloc(size_t);
int *p;
...
p = (int *) wrong_return_type_malloc( foo );
...
}

Now, look at that cast. In the current program, it's *hiding*
the error from the compiler. (Remember that a cast always says
to the compiler, "Be quiet and let me do this my way, right or
wrong.") So this program will compile without diagnostics, and
run, and crash, because we're expecting 'malloc' to return an
'int' (by mechanism A) when really it's returning a 'void *' (by
mechanism B). Really, some machines will actually use different
registers for different types, and so on.
So our program crashes at runtime -- or, insidiously, doesn't
crash until the day of the big demo, when the boss is around.

So can i do something like this :
typedef struct mystr{
char *p;
int i[10];
}my_str;

int main (void)
{
void *data;
my_str *use;

data = malloc ( sizeof my_str);
use = ( my_str*)data ;
use->i[0] = 3333;

free ( use );
return 0;
}
So, everytime i need to use 'malloc', get its return value in a '
void* ' variable and then use this variable to cast according to my
requirement which can be of struct/int/char type. ? Is this correct.

Also what actually happens if variable 'p' is of my_str type.

p = malloc ( *p ); /* which seems to be the most suggested option ! */

Just a little finer maybe...

#include <stdlib.h>

typedef struct mystr {
struct mystr *p;
int i[10];
} my_str;

int main(void) {
my_str *use;
use = malloc( sizeof *use );
use->i[0] = 3333;
use->p = malloc( sizeof *use->p );
use->p->i[0] = 4444;

free( use->p );
free( use );
return 0;
}
--
Joe Wright mailto:jo********@earthlink.net
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 13 '05 #52
"Joe Wright" <jo********@earthlink.net> wrote in message
news:3F**********@earthlink.net...
....
Just a little finer maybe...

#include <stdlib.h>

typedef struct mystr {
struct mystr *p;
int i[10];
} my_str;

int main(void) {
my_str *use;
use = malloc( sizeof *use );
use->i[0] = 3333;
use->p = malloc( sizeof *use->p );
use->p->i[0] = 4444;

free( use->p );
free( use );
return 0;
}


You should always check whether or not malloc returns a null pointer.

--
Peter
Nov 13 '05 #53
Ravi Uday wrote:

[ snip ]
int main(void)
{
int wrong_return_type_malloc(size_t);
int *p;
...
p = (int *) wrong_return_type_malloc( foo );
...
}

Now, look at that cast. In the current program, it's *hiding*
the error from the compiler. (Remember that a cast always says
to the compiler, "Be quiet and let me do this my way, right or
wrong.") So this program will compile without diagnostics, and
run, and crash, because we're expecting 'malloc' to return an
'int' (by mechanism A) when really it's returning a 'void *' (by
mechanism B). Really, some machines will actually use different
registers for different types, and so on.
So our program crashes at runtime -- or, insidiously, doesn't
crash until the day of the big demo, when the boss is around.

So can i do something like this :
typedef struct mystr{
char *p;
int i[10];
}my_str;

int main (void)
{
void *data;
my_str *use;

data = malloc ( sizeof my_str);
use = ( my_str*)data ;
use->i[0] = 3333;

free ( use );
return 0;
}
So, everytime i need to use 'malloc', get its return value in a '
void* ' variable and then use this variable to cast according to my
requirement which can be of struct/int/char type. ? Is this correct.

Also what actually happens if variable 'p' is of my_str type.

p = malloc ( *p ); /* which seems to be the most suggested option ! */

Just a little finer maybe...

#include <stdlib.h>

typedef struct mystr {
struct mystr *p;
int i[10];
} my_str;

int main(void) {
my_str *use;
use = malloc( sizeof *use );
use->i[0] = 3333;
use->p = malloc( sizeof *use->p );
use->p->i[0] = 4444;

free( use->p );
free( use );
return 0;
}
--
Joe Wright mailto:jo********@earthlink.net
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 13 '05 #54
"Joe Wright" <jo********@earthlink.net> wrote in message
news:3F**********@earthlink.net...
....
Just a little finer maybe...

#include <stdlib.h>

typedef struct mystr {
struct mystr *p;
int i[10];
} my_str;

int main(void) {
my_str *use;
use = malloc( sizeof *use );
use->i[0] = 3333;
use->p = malloc( sizeof *use->p );
use->p->i[0] = 4444;

free( use->p );
free( use );
return 0;
}


You should always check whether or not malloc returns a null pointer.

--
Peter
Nov 13 '05 #55
Peter Nilsson wrote:

"Joe Wright" <jo********@earthlink.net> wrote in message
news:3F**********@earthlink.net...
...
Just a little finer maybe...

#include <stdlib.h>

typedef struct mystr {
struct mystr *p;
int i[10];
} my_str;

int main(void) {
my_str *use;
use = malloc( sizeof *use );
use->i[0] = 3333;
use->p = malloc( sizeof *use->p );
use->p->i[0] = 4444;

free( use->p );
free( use );
return 0;
}


You should always check whether or not malloc returns a null pointer.

Why? This is not a trick question. Think about it.
--
Joe Wright mailto:jo********@earthlink.net
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 13 '05 #56
On Sat, 06 Sep 2003 19:29:22 +0000, Joe Wright wrote:
Peter Nilsson wrote:

"Joe Wright" <jo********@earthlink.net> wrote in message
news:3F**********@earthlink.net...
...
> Just a little finer maybe...
>
> 0 #include <stdlib.h>
> 1
> 2 typedef struct mystr {
> 3 struct mystr *p;
> 4 int i[10];
> 5 } my_str;
> 6
> 7 int main(void) {
> 8 my_str *use;
> 9 use = malloc( sizeof *use );
> 10 use->i[0] = 3333;
> 11 use->p = malloc( sizeof *use->p );
> 12 use->p->i[0] = 4444;
> 13
> 14 free( use->p );
> 15 free( use );
> 16 return 0;
> 17 }


You should always check whether or not malloc returns a null pointer.

Why? This is not a trick question. Think about it.


Let me try.

By 7.20.3.3.3, malloc may return a null pointer.

By 6.3.2.3.3, a null pointer is guaranteed to compare unequal to a
pointer to any object. Therefore, a null pointer points at no
object.

By 6.5.2.3.4, the value of a -> expression is that of the member
(named by the identifier after the ->) of the object to which the
postfix expression before -> points.

If, after line 9, use is a null pointer, it points at no object and
the expression use->i therefore has undefined value and the attempt
to build the sum (use->i + 0) (as in 6.5.2.1.2) results in undefined
behavior.

Nov 13 '05 #57
Sheldon Simms wrote:

On Sat, 06 Sep 2003 19:29:22 +0000, Joe Wright wrote:
Peter Nilsson wrote:

"Joe Wright" <jo********@earthlink.net> wrote in message
news:3F**********@earthlink.net...
...
> Just a little finer maybe...
>
> 0 #include <stdlib.h>
> 1
> 2 typedef struct mystr {
> 3 struct mystr *p;
> 4 int i[10];
> 5 } my_str;
> 6
> 7 int main(void) {
> 8 my_str *use;
> 9 use = malloc( sizeof *use );
> 10 use->i[0] = 3333;
> 11 use->p = malloc( sizeof *use->p );
> 12 use->p->i[0] = 4444;
> 13
> 14 free( use->p );
> 15 free( use );
> 16 return 0;
> 17 }

You should always check whether or not malloc returns a null pointer.

Why? This is not a trick question. Think about it.


Let me try.

By 7.20.3.3.3, malloc may return a null pointer.

By 6.3.2.3.3, a null pointer is guaranteed to compare unequal to a
pointer to any object. Therefore, a null pointer points at no
object.

By 6.5.2.3.4, the value of a -> expression is that of the member
(named by the identifier after the ->) of the object to which the
postfix expression before -> points.

If, after line 9, use is a null pointer, it points at no object and
the expression use->i therefore has undefined value and the attempt
to build the sum (use->i + 0) (as in 6.5.2.1.2) results in undefined
behavior.


OK Sheldon. Right you are.

Let me appologise to you and the group for lame humour. My point was
that the simple example program was not meant to do anything useful
except to make the use of pointers a little clearer. Including malloc()
error checking would add lots of code without contributing to the
exposition of pointer usage.

In practice, almost all of my programs check the return value of
malloc() and friends something like this..

if ((ptr = malloc( N * sizeof *ptr )) == NULL)
fputs("Malloc Failed\n", stderr), exit(EXIT_FAILURE);

...but I have yet to see it fail unexpectedly. Ever. In twenty years! I
know this is annecdotal how about the rest of you?

--
Joe Wright mailto:jo********@earthlink.net
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 13 '05 #58
Joe Wright <jo********@earthlink.net> wrote:
[...]
In practice, almost all of my programs check the return value of
malloc() and friends something like this..

if ((ptr = malloc( N * sizeof *ptr )) == NULL)
fputs("Malloc Failed\n", stderr), exit(EXIT_FAILURE);

..but I have yet to see it fail unexpectedly. Ever. In twenty years! I
know this is annecdotal how about the rest of you?


If you use an environment that supports user resource limits, try this
command (bourne shell syntax):

ulimit -Sv 4096

- Kevin.

Nov 13 '05 #59
Kevin Easton wrote:
Joe Wright <jo********@earthlink.net> wrote:
[...]
In practice, almost all of my programs check the return value of
malloc() and friends something like this..

if ((ptr = malloc( N * sizeof *ptr )) == NULL)
fputs("Malloc Failed\n", stderr), exit(EXIT_FAILURE);

..but I have yet to see it fail unexpectedly. Ever. In twenty years! I
know this is annecdotal how about the rest of you?


If you use an environment that supports user resource limits, try this
command (bourne shell syntax):

ulimit -Sv 4096

- Kevin.


How much do I owe you guys? :-) Seriously, these are great answers.
Thank you!

--Steve Zimmerman
################ Experiment 7 (malloc) #####################

#include <stdio.h>
#include <stdlib.h>

int main()
{
char *h = NULL;
char *g;

g = malloc(30);

if (h == NULL)
fprintf(stderr, "No memory allocation\n");
else
printf("Successful memory allocation\n");

free(g);

return 0;
}

Output: No memory allocation

############### Experiment 8 (malloc) ##########################

#include <stdio.h>
#include <stdlib.h>

int main()
{
char *ptr;

/* The following four lines are copyright (c) Joe Wright. */

if ((ptr = malloc( 30 * sizeof *ptr )) == NULL) {
fputs ("Malloc failed\n", stderr);
exit(EXIT_FAILURE);
}

else {
fputs ("Malloc succeeded\n", stdout);
exit(EXIT_SUCCESS);
}
}

Output: Malloc succeeded

Nov 13 '05 #60

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

Similar topics

2
by: Steve Zimmerman | last post by:
Esteemed contributors to clc: Thank you for all the responses. Experiments 2 and 3 below are identical, except that experiment 2 does not call free(), while experiment 3 does. With such a...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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,...
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,...
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: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.