473,608 Members | 2,412 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 #1
59 5152
Steve Zimmerman <st******@sonic .net> wrote in
news:3F******** ******@sonic.ne t:
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));
This is a problem. If you had neglected to include <stdlib.h> there would
be no prototype for malloc(), thus it would return an integer. Your cast
would have hidden this mistake. In C (but not C++), we do not cast the
return value of malloc(). Second, it is best to specify the size of the
object not its type. That way, if the type of the object changes you don't
have to find the malloc() call and change that line too. E.g.

president = malloc(sizeof *president);

Next, be sure you were handed a valid pointer, malloc() can fail. If it
does, maybe you could return EXIT_FAILURE.
strcpy(presiden t->name, "George Washington");
Use strncpy() and tell strncpy not to exceed sizeof president->name - 1.
president->next = (struct pres *)malloc(sizeof (struct pres));
(Same malloc() comments here too).
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;
}


--
- Mark ->
--
Nov 13 '05 #2

"Steve Zimmerman" <st******@sonic .net> wrote in message
news:3F******** ******@sonic.ne t...
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>
Add this definition to avoid magic numbers
#define PRES_NAME_LEN 25


int main()
{
struct pres {
char name[25];
struct pres *next;
};
Use PRES_NAME_LEN instead of magic 25.

struct pres *president;

president = (struct pres *)malloc(sizeof (struct pres)); You have to check if malloc was successful.
The condition to continue execution is (president != NULL)
Just a minor remark;
You don't have to cast the result from malloc as long as stdlib.h is
included (and it should be!).

strcpy(presiden t->name, "George Washington"); Oops.
What happens if the string exceeds the size of "name" field in the struct?
Something will be destroyed and overwritten!
Protect the field from overflow by using
strncpy(preside nt->name, "George Washington", PRES_NAME_LEN);
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


Finally, you must free the memory you've allocated when this program will
transform from prototype to a real application.

Mikael T
Nov 13 '05 #3
Steve Zimmerman wrote:

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>
Non-Standard header. It's anybody's guess what it might do.
#include <string.h>

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

struct pres *president;

president = (struct pres *)malloc(sizeof (struct pres));
Two minor points: the cast is unnecessary, and it would be
better to write `sizeof *president'. One major gaffe: malloc()
can fail and return NULL, and you should check for this before
trying to use the possibly-not-allocated memory.
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);
"%i" is for converting integers, not pointer values. You
need to use "%p", and you need to convert the pointer value
from a `struct pres*' to a `void*'.
return 0;
}

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

--Steve


--
Er*********@sun .com
Nov 13 '05 #4
On Wed, 03 Sep 2003 14:23:55 GMT,
Steve Zimmerman <st******@sonic .net> wrote
in Msg. <3F************ **@sonic.net>
This program compiles fine, but are there any hidden dangers
in it, or is it ok? president = (struct pres *)malloc(sizeof (struct pres));


Who taught you to cast malloc()'s return value? Others have pointed out
the reasons why this is bad; I just want to know where you got the idea
from.

--Daniel

--
"With me is nothing wrong! And with you?" (from r.a.m.p)
Nov 13 '05 #5


Steve Zimmerman wrote:

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"); Danger - what if the name is longer than 24 characters?

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


--
Fred L. Kleinschmidt
Associate Technical Fellow
Boeing Common User Interface Services
Nov 13 '05 #6
"Mark A. Odell" <no****@embedde dfw.com> wrote:
Steve Zimmerman <st******@sonic .net> wrote:
strcpy(presiden t->name, "George Washington");


Use strncpy() and tell strncpy not to exceed sizeof president->name - 1.


strncpy is the wrong tool for this job. If the string supplied is
too large it will leave the array unterminated, so there is not a
valid string. Use strncat instead, by zeroing the string first:
*president->name = 0; /* or president->name[0] = '\0'; */
strncat(preside nt->name, "George Washington", sizeof president->name - 1);
printf("The first structure has been created:\n");
printf("preside nt->name = %s\n", president->name);
printf("next structure address = %i\n", president->next);


This is undefined behaviour. The printf is looking for an int, but you
never supplied an int, you supplied a pointer to struct pres, which
may be stored in an entirely different place.

You should print pointers with the %p conversion, and remember to
cast the pointer to (void *), as that is the type expected by %p.

printf("next structure address = %p\n", (void*)presiden t->next);

--
Simon.
Nov 13 '05 #7
"Mikael Thorgren" <mi************ *@senet.abb.se> wrote:
strcpy(presiden t->name, "George Washington");


Oops.
What happens if the string exceeds the size of "name" field in the struct?
Something will be destroyed and overwritten!
Protect the field from overflow by using
strncpy(preside nt->name, "George Washington", PRES_NAME_LEN);


You want strncat instead, because strncpy doesn't null-terminate
the string if the length argument is exhausted. You also want to
specify PRES_NAME_LEN - 1 here, to leave room for the null char.

--
Simon.
Nov 13 '05 #8
"Mikael Thorgren" <mi************ *@senet.abb.se> writes:
"Steve Zimmerman" <st******@sonic .net> wrote in message
news:3F******** ******@sonic.ne t...
struct pres {
char name[25];
struct pres *next;
};


Use PRES_NAME_LEN instead of magic 25.
strcpy(presiden t->name, "George Washington");


What happens if the string exceeds the size of "name" field in the struct?
Something will be destroyed and overwritten!
Protect the field from overflow by using
strncpy(preside nt->name, "George Washington", PRES_NAME_LEN);


This is still problematic, as `strncpy' does not write a '\0' character if
the source string has length equal to or greater than the length specified
in the third argument.

A better solution:

strncpy (president->name, "George Washington", PRES_NAME_LEN - 1);
president->name [PRES_NAME_LEN - 1] = '\0';

Martin
Nov 13 '05 #9
bd
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Steve Zimmerman wrote:
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>
No such header. malloc(), calloc(), and free() are in stdlib.h
#include <string.h>

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

struct pres *president;

president = (struct pres *)malloc(sizeof (struct pres));
The cast is unnecessary, and could prevent the compiler warning you if you
accidentally forget to include stdlib.h.

strcpy(presiden t->name, "George Washington");
president->next = (struct pres *)malloc(sizeof (struct pres));
See above.

printf("The first structure has been created:\n");
printf("preside nt->name = %s\n", president->name);
printf("next structure address = %i\n", president->next);
%i is for an int. president->next is a struct pres *. Try;
printf("next structure address = %p\n", (void *)president->next);
return 0;
}


- --
There's another way to survive. Mutual trust -- and help.
-- Kirk, "Day of the Dove", stardate unknown

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.2 (GNU/Linux)

iD4DBQE/VjfEx533NjVSos4 RAnHNAJd0IU66hK YlV4fDyPlNCSTGq aOeAJ9oWWaS
BDUTzHsSo6ZqFeR 3WZR8AA==
=msbg
-----END PGP SIGNATURE-----
Nov 13 '05 #10

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
8501
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
8483
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...
0
8349
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
6820
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
6015
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
5479
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3967
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...
0
4030
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1607
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.