473,854 Members | 1,495 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(presiden t->name, "George Washington");
president->next = (struct pres *)malloc(sizeof (struct pres));

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

return 0;
}

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

--Steve

Nov 13 '05
59 5232
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_ty pe_malloc(size_ t);
int *p;
...
p = (int *) wrong_return_ty pe_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.ne t
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 13 '05 #52
"Joe Wright" <jo********@ear thlink.net> wrote in message
news:3F******** **@earthlink.ne t...
....
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_ty pe_malloc(size_ t);
int *p;
...
p = (int *) wrong_return_ty pe_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.ne t
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 13 '05 #54
"Joe Wright" <jo********@ear thlink.net> wrote in message
news:3F******** **@earthlink.ne t...
....
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********@ear thlink.net> wrote in message
news:3F******** **@earthlink.ne t...
...
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.ne t
"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********@ear thlink.net> wrote in message
news:3F******** **@earthlink.ne t...
...
> 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********@ear thlink.net> wrote in message
news:3F******** **@earthlink.ne t...
...
> 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_FAILU RE);

...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.ne t
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 13 '05 #58
Joe Wright <jo********@ear thlink.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_FAILU RE);

..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********@ear thlink.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_FAILU RE);

..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("Success ful 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_FAILU RE);
}

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

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
660
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 trivial program, is it safe not to call free()? Are there dangers in experiment 2 that experiment 3 avoids?
0
9901
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
11024
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
10679
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10756
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9513
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
7914
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
5741
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...
1
4560
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
3186
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.