Basic Use of Malloc

K

kent lavallie

Hi. I am an amature c hobbyist and I wish to begin using malloc as I
have been told that running executables from executables is a less
than elegant way to manage memory use. I need basic examples so me and
my compiler can get familliar with malloc. Please give examples that
do not contain nested assignments and the like as I will get lost
quite easily. As an example of my rudimentary style take a look at how
I create an array and assign a pointer to it:

unsigned long arraysize = 50;
char chArray[arraysize];
char *ptrChArray;
ptrChArray = chArray;

I need a few examples of malloc's proper use that are in the same
rudimentary style. Thank you so much for your time. kentinjapan
 
S

Steve Zimmerman

kent said:
Hi. I am an amature c hobbyist and I wish to begin using malloc as I
have been told that running executables from executables is a less
than elegant way to manage memory use. I need basic examples so me and
my compiler can get familliar with malloc. Please give examples that
do not contain nested assignments and the like as I will get lost
quite easily. As an example of my rudimentary style take a look at how
I create an array and assign a pointer to it:

unsigned long arraysize = 50;
char chArray[arraysize];
char *ptrChArray;
ptrChArray = chArray;

I need a few examples of malloc's proper use that are in the same
rudimentary style. Thank you so much for your time. kentinjapan

Also, you might try

http://www.c-for-dummies.com/lessons/chapter.17

I found the _C for Dummies_ material helpful when I was new to C.

--Steve
 
J

Jeff

kent lavallie said:
Hi. I am an amature c hobbyist and I wish to begin using malloc as I
have been told that running executables from executables is a less
than elegant way to manage memory use. I need basic examples so me and
my compiler can get familliar with malloc. Please give examples that
do not contain nested assignments and the like as I will get lost
quite easily. As an example of my rudimentary style take a look at how
I create an array and assign a pointer to it:

unsigned long arraysize = 50;
char chArray[arraysize];
char *ptrChArray;
ptrChArray = chArray;

I need a few examples of malloc's proper use that are in the same
rudimentary style. Thank you so much for your time. kentinjapan

This is an example:

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

int main()
{
char *buffer;
char *string1 = "Hello ";

buffer = malloc(30);
strcpy(buffer, string1);
strcat(buffer, "World.");

puts(buffer);
return 0;
}
 
N

Nils Petter Vaskinn

I need a few examples of malloc's proper use that are in the same
rudimentary style. Thank you so much for your time. kentinjapan

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

int main()
{
/* Declare a pointer, TYPE can be anything: int struct double whatever */
TYPE *array;

/* Allocate memory to hold 50 of whatever the type array points to */
array = malloc(50 * sizeof(*array));
if (! array) {
printf("Couldn't allocate memory\n");
exit(1);
}

do_something(array);

/* We need a bigger array */
TYPE *tmp;
/* Realloc allocates a new block, and copies the contents
(as far as possible */
tmp = realloc(array, 70 * sizeof(*array));
if (! tmp) {
printf("Couldn't reallocate memory\n");
exit(1);
}

array = tmp;

do_something_else(array);

/* release the memory when we're done */
free(array);

return 0;
}

hth
 
M

Martijn

Jeff said:
buffer = malloc(30);
strcpy(buffer, string1);
strcat(buffer, "World.");

Not a point of critisism to the example, but something to watch out for: be
aware that this allocates space for 30 _bytes_, so don't go and try to store
30 integers in that memory. If that's what you want, try this:

int *buffer;
buffer = malloc(30 * sizeof(int));

Good luck,
 
I

Irrwahn Grausewitz

Hi Kent,

good to see you found your way to c.l.c. :)

Hi. I am an amature c hobbyist and I wish to begin using malloc as I
have been told that running executables from executables is a less
than elegant way to manage memory use. I need basic examples so me and
my compiler can get familliar with malloc. Please give examples that
do not contain nested assignments and the like as I will get lost
quite easily. As an example of my rudimentary style take a look at how
I create an array and assign a pointer to it:

unsigned long arraysize = 50;
char chArray[arraysize];
char *ptrChArray;
ptrChArray = chArray;

I need a few examples of malloc's proper use that are in the same
rudimentary style. Thank you so much for your time. kentinjapan

Besides the examples I gave to you on c.l.c.moderated and by mail,
here is one more:

/* -------8<----------------- */

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

#define TEXT_SIZE 1000

int main( void )
{
char *text, *copy, *cp;
int i, len, ecount;

/* Allocate some memory, checking for error:
*/
text = malloc( TEXT_SIZE );
if ( text == NULL )
{
printf("Memory allocation for 'text' failed!");
exit( EXIT_FAILURE );
}

/* Read some user input into text:
*/
printf( "\nPlease enter some text: " );
fgets( text, TEXT_SIZE, stdin );

/* Now we step through text, counting 'e's
** as we go, using a pointer-to-char:
*/
ecount = 0;
for ( cp = text; *cp != '\0'; cp++ )
{
if ( *cp == 'e' )
ecount++;
}
printf( "The text you entered contains %d 'e's.\n",
ecount );

/* Now we use array syntax instead, changing
** all 'u's to 'x's as we go:
*/
for ( i = 0; i < TEXT_SIZE; i++ )
{
if ( text[ i ] == 'u' )
text[ i ] = 'x';
}
printf( "'u' changed to 'x': %s", text );

/* Now we allocate just enough space to hold
** the text the user entered (note that we have
** to add 1 to hold the terminating '\0'):
*/
len = strlen( text ) + 1;
copy = malloc( len );
if ( copy == NULL )
{
printf("Memory allocation for 'copy' failed!");
exit( EXIT_FAILURE );
}

/* Copy from 'text' to 'copy':
*/
strcpy( copy, text );
printf( "The copy reads: %s", copy );

return EXIT_SUCCESS;
}

/* -------8<----------------- */

Regards

Irrwahn
 
J

Joe Wright

Martijn said:
Not a point of critisism to the example, but something to watch out for: be
aware that this allocates space for 30 _bytes_, so don't go and try to store
30 integers in that memory. If that's what you want, try this:

int *buffer;
buffer = malloc(30 * sizeof(int));

Good luck,

The clc canon eschews magic numbers and unnecessary type names. Regard..

int *buffer, size = 30;
buffer = malloc( size * sizeof *buffer );
 
M

Martin Dickopp

Irrwahn Grausewitz said:
printf("Memory allocation for 'text' failed!");
exit( EXIT_FAILURE );

It is implementation-defined whether or not the last line written to
a text stream requires a terminating new-line character. For maximal
portability, you might want to write a '\n' as the last character.
printf( "\nPlease enter some text: " );
fgets( text, TEXT_SIZE, stdin );

Add `fflush (stdout);' after the `printf' function call. Otherwise, the
text is not guaranteed to be written before the `fgets' call.
printf("Memory allocation for 'copy' failed!");
exit( EXIT_FAILURE );

Same comment as the first one.
printf( "The copy reads: %s", copy );
return EXIT_SUCCESS;

Same comment as immediately above.

Martin
 
I

Irrwahn Grausewitz

Martin Dickopp said:
It is implementation-defined whether or not the last line written to
a text stream requires a terminating new-line character. For maximal
portability, you might want to write a '\n' as the last character.
Got me. :)
Add `fflush (stdout);' after the `printf' function call. Otherwise, the
text is not guaranteed to be written before the `fgets' call.
Again. Doh!
Same comment as the first one.
You're so right... sigh...
Same comment as immediately above.
Ah, IMHO /this one/ is OK, because I left the '\n' in 'text'
and therefore in 'copy', thus I should be safe in this case,
shouldn't I?

Irrwahn
 
M

Martin Dickopp

Irrwahn Grausewitz said:
Ah, IMHO /this one/ is OK, because I left the '\n' in 'text' and
therefore in 'copy', thus I should be safe in this case, shouldn't I?

The `fgets' function only stores a newline character if it encounters one
while reading the number of characters it is supposed to read maximally.
If the user enters more characters, or the end-of-file condition or an
error occurs, no newline character is stored.

Which reminds me: Since you don't check the return value of `fgets', it
could also happen that `text' remains unchanged (if end-of-file occurs
before any characters have been read) or becomes indeterminate (if an
error occurs). In both cases, you invoke undefined behavior. :)

Martin
 
I

Irrwahn Grausewitz

Martin Dickopp said:
The `fgets' function only stores a newline character if it encounters one
while reading the number of characters it is supposed to read maximally.
If the user enters more characters, or the end-of-file condition or an
error occurs, no newline character is stored.

Which reminds me: Since you don't check the return value of `fgets', it
could also happen that `text' remains unchanged (if end-of-file occurs
before any characters have been read) or becomes indeterminate (if an
error occurs). In both cases, you invoke undefined behavior. :)

Oh dear! =%O

Hm, at least I wrote: int main( void )

:)
 
E

Emmanuel Delahaye

Not a point of critisism to the example, but something to watch out for:
be aware that this allocates space for 30 _bytes_, so don't go and try
to store 30 integers in that memory. If that's what you want, try this:

int *buffer;
buffer = malloc(30 * sizeof(int));

or simply:

any_type_except_void *buffer = malloc (30 * sizeof *buffer);
 
E

Emmanuel Delahaye

In 'comp.lang.c' said:
The clc canon eschews magic numbers and unnecessary type names. Regard..

int *buffer; size_t const size = 30;
buffer = malloc( size * sizeof *buffer );
 
P

Philip Ludlam

Hi. I am an amature c hobbyist and I wish to begin using malloc as I
have been told that running executables from executables is a less
than elegant way to manage memory use. I need basic examples so me and
my compiler can get familliar with malloc. Please give examples that
do not contain nested assignments and the like as I will get lost
quite easily.

This should be a simple one to understand:

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

int main(void)
{
char* c;
if ((c = malloc( 10)) == NULL)
{
fprintf (stderr, "Unable to allocate memory.\n");
exit (EXIT_FAILURE);
}

exit (EXIT_SUCCESS);
}

Don't be confused about the if and malloc being on the same line - look
at it from the inside pair of brackets outwards:

( 10) /* 10 is the argument passed to malloc */
(c = malloc( 10)) /* malloc's return value is assigned to c */
if ((c = malloc( 10)) == NULL) /* if malloc's return value is NULL
then the condition is true /*

Yours,

Phil L.
 
J

Jeff

Joe Wright said:
The clc canon eschews magic numbers and unnecessary type names. Regard..

int *buffer, size = 30;
buffer = malloc( size * sizeof *buffer );

Yes, we shoudn't put magic number in the code. Also, i didn't show a
"free(buffer)" in my code to indicate that we should free the memory we
allocated.
 
R

Richard Heathfield

Steve said:

Only, perhaps, as an example of how /not/ to use malloc.

Allow me to post some code from that site, which I'll "enquote" to show that
it's not my code (but please understand that the quote characters do not
mean that I'm claiming you wrote it!):
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

Non-standard header.
#include <string.h>

void main()

Undefined behaviour.
{
struct pres {
char name[25];
struct pres *next;
};

Generally speaking, it's poor style to define a type inside main(), because
a serious program would expect to do little of its work in main() itself.
This, however, is not a serious program, so we'll let it off.
struct pres *president;

/* Create the first item in the list */

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

Unnecessary cast, clumsy sizeof.

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

Completely failed to check the return value from malloc.

Hmmm, "George Washington" sounds familiar. Have you posted this elsegroup
recently?
president->next = (struct pres *)malloc(sizeof(struct pres));

Same comments apply as to previous malloc.
/* Stop here and display the results */

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

This last line exhibits undefined behaviour. Even if we assume president is
not NULL, it should read:

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

No return value from a function that is required to return int.

In short, the code sucks. The book makes no attempt to teach the C language,
but rather the author's personal, flawed understanding of that language.
 
P

pete

Richard said:
The book makes no attempt to teach the C language,
but rather the author's personal,
flawed understanding of that language.

He's one of those, who has deduced what C is,
from his experience with his compiler.

"Note that it's "might" screw things up. In fact, even the void main()
thing is an iffy. I've gotten complaints from various
self-proclaimed C Lords, some of which are even USENET C Jerks,
who proclaim the evils of void main() and
that I'm an ass for every propogating such nonsense.

Perhaps I am an ass. But not one of these C poobahs has
yet to provide a specific instance of void main() or the lack of a
return statement actually screwing anything up.
No, they just speak in generalities, which is typical
(most likely because their knowledge of C is weak
and their self-importance overrated)."
 
K

Koster

I'm far from an experienced C programmer, but if you ask me, ignoring standards
because your compiler happens to generate the right instructions from something
incorrect, is sheer folly. A good example of where this is deadly is with HTML
(and the browsers' interpreters). The HTML writers among us all know of the
torment that the different browsers place on us by differing standards and
behaviours, and as such I learned everything I know of HTML from specifications
-- not by example. I'm sure similar things occur between C compilers.

If I were learning the C language (which to a certain extent I still am), I
would make sure my code is standards-compliant, not only because it would be
more easily ported to different platforms and compilers, but also it looks much
more impressive when your boss reads through your code, assuming of course
he/she knows the difference.
If I were an employer, an employee would not be presenting himself as a good
programmer if I the first thing I saw was void main(), am I right?

Just like a piano student must learn good technique in order to be able to play
a piece impressively, so should the student of C strive to write correct code.
Remember: unlike the pianist, us programmers cannot fall back upon 'artistic
license'...

My two cents,
Koster.




|Richard Heathfield wrote:
|
|> The book makes no attempt to teach the C language,
|> but rather the author's personal,
|> flawed understanding of that language.
|
|He's one of those, who has deduced what C is,
|from his experience with his compiler.
|
|"Note that it's "might" screw things up. In fact, even the void main()
| thing is an iffy. I've gotten complaints from various
| self-proclaimed C Lords, some of which are even USENET C Jerks,
| who proclaim the evils of void main() and
| that I'm an ass for every propogating such nonsense.
|
| Perhaps I am an ass. But not one of these C poobahs has
| yet to provide a specific instance of void main() or the lack of a
| return statement actually screwing anything up.
| No, they just speak in generalities, which is typical
|(most likely because their knowledge of C is weak
| and their self-importance overrated)."
 
J

John Bode

Hi. I am an amature c hobbyist and I wish to begin using malloc as I
have been told that running executables from executables is a less
than elegant way to manage memory use. I need basic examples so me and
my compiler can get familliar with malloc. Please give examples that
do not contain nested assignments and the like as I will get lost
quite easily. As an example of my rudimentary style take a look at how
I create an array and assign a pointer to it:

unsigned long arraysize = 50;
char chArray[arraysize];
char *ptrChArray;
ptrChArray = chArray;

I need a few examples of malloc's proper use that are in the same
rudimentary style. Thank you so much for your time. kentinjapan

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

#define ARRSIZE 50 /* same for all arrays */

int main (void)
{
char *ptrChArray = NULL;

ptrChArray = malloc (ARRSIZE * sizeof *ptrChArray);
if (!ptrChArray)
{
printf ("malloc() failed for %d elements of size %lu\n",
ARRSIZE, sizeof *ptrChArray);
exit (EXIT_FAILURE);
}

/* do stuff with ptrChArray here */
strcpy (ptrChArray, "This is a test");
printf ("%s", ptrChArray);

/* free the memory when we're done with it */
free (ptrChArray);

return 0;
}

Slightly more complicated example: allocating and freeing 2D arrays of int.

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

/* allocate int arr[d0][d1] */
int **new2Darr (size_t d0, size_t d1)
{
int **arr = NULL;

/* allocate an array of d0 elements of type int* */
arr = malloc (d0 * sizeof *arr);
if (arr)
{
size_t i;
for (i = 0; i < d0; i++)
{
/* allocate an array of d1 elements of type int */
arr = malloc (d1 * sizeof **arr);
if (!arr)
{
break;
}
}

/*
** If all of the above malloc() operations succeed,
** i should equal d0. If it's less, then a call
** to malloc has failed. If that happens, we free
** all the memory that has been allocated to this
** point and return NULL.
*/
if (i < d0)
{
while (--i >= 0)
{
free (arr);
}
free (arr);
arr = NULL;
}
}
return (arr);
}

void delete2Darr (int ***arr, size_t d0)
{
int i;
if (*arr)
{
for (i = 0; i < d0; i++)
{
free (*arr);
}
free (*arr);
*arr = NULL;
}
}

int main (void)
{
int **a1 = NULL;

a1 = new2Darr (10, 20); /* int a1[10][20] */

if (a1)
{
/* do fun stuff with a1 */
a1[0][0] = ...;
a1[0][1] = ...;

/*
** When we're done with a1, we should explicitly
** free the memory. Note that we have to remember
** at least the first dimension of the array to
** properly deallocate all of the 1d arrays; there's
** no way to retrieve this information from the pointer
** itself.
*/
delete2Darr (&a1, 10);
}

exit (0);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,079
Messages
2,570,574
Members
47,206
Latest member
Zenden

Latest Threads

Top