473,770 Members | 2,147 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Basic Use of Malloc

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
Nov 13 '05 #1
21 34394
kent lavallie wrote:
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

Nov 13 '05 #2

"kent lavallie" <ke**********@y ahoo.ca> wrote in message
news:d6******** *************** ***@posting.goo gle.com...
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;
}

--
Jeff
Nov 13 '05 #3
On Tue, 09 Sep 2003 20:56:56 -0700, kent lavallie wrote:
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(ar ray);

/* 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_el se(array);

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

return 0;
}

hth

--
NPV
"Linux is to Lego as Windows is to Fisher Price." - Doctor J Frink

Nov 13 '05 #4
Jeff wrote:
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,

--
Martijn
http://www.sereneconcepts.nl
Nov 13 '05 #5
Hi Kent,

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

ke**********@ya hoo.ca (kent lavallie) wrote:
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
--
What does this red button do?
Nov 13 '05 #6
Martijn wrote:

Jeff wrote:
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,

--
Martijn
http://www.sereneconcepts.nl


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

int *buffer, size = 30;
buffer = malloc( size * sizeof *buffer );
--
Joe Wright mailto:jo****** **@earthlink.ne t
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 13 '05 #7
Irrwahn Grausewitz <ir*****@freene t.de> writes:
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
Nov 13 '05 #8
Martin Dickopp <ex************ *@zero-based.org> wrote:
Irrwahn Grausewitz <ir*****@freene t.de> writes:
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.

Got me. :)
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.

Again. Doh!
printf("Memory allocation for 'copy' failed!");
exit( EXIT_FAILURE );
Same comment as the first one.

You're so right... sigh...
printf( "The copy reads: %s", copy );
return EXIT_SUCCESS;


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
--
What does this red button do?
Nov 13 '05 #9
Irrwahn Grausewitz <ir*****@freene t.de> writes:
Martin Dickopp <ex************ *@zero-based.org> wrote:
Irrwahn Grausewitz <ir*****@freene t.de> writes:
printf( "The copy reads: %s", copy );
return EXIT_SUCCESS;


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?


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
Nov 13 '05 #10

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

Similar topics

18
2129
by: steve | last post by:
I'm trying to create a structure of three pointers to doubles. For which I have: typedef struct { double *lst_t, *lst_vc, *lst_ic; } last_values; I then need to allocate space for last_values as well as assign the value of a pointer to the assigned space. Which I think I'm doing by using:
9
1284
by: shan_rish | last post by:
Hi CLCers, I coded a function to allocate memory and i am passing a pointer to the function. The code is compiling but throws error and closes while executing. The program is as below: #include<stdio.h> #include<stdlib.h> int main() { int *p; void mem_fun(int *i);
21
470
by: ramu | last post by:
Hi, Will the memory allocated by malloc and realloc be contiguous? regards
25
2265
by: Why Tea | last post by:
Thanks to those who have answered my original question. I thought I understood the answer and set out to write some code to prove my understanding. The code was written without any error checking. --- #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct {
58
4684
by: Jorge Peixoto de Morais Neto | last post by:
I was reading the code of FFmpeg and it seems that they use malloc just too much. The problems and dangers of malloc are widely known. Malloc also has some overhead (although I don't know what is the overhead of automatic variable sized arrays, I suspect it is smaller than that of malloc), although I'm not too worried about it. I was thinking that, with C99's variable length arrays, malloc shouldn't be needed most of the time. But I'm...
1
1888
by: Kevin | last post by:
Hi all, I clearly have an issue with some pointers, structures, and memory allocation. Its probably pritty basic, but I'm a little stuck. Any help would be greatly appreciated. I'd like to instantiate an arbitrary number of arrays of arbitrary size in function_a, copy the pointers, store the data, and free any unused memory. My basic structure is as follows:
71
19131
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 problem? I cannot see why using malloc instead of new does not give the same result.
173
8184
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. OTOH, if you're allocating a gigabyte for a large array, this might fail, so you should definitely check for a NULL return.
26
3846
by: Muzammil | last post by:
whats the beauty of "malloc" over "new" why its helpful for programmer.for its own memory area.??
0
9619
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
9454
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10102
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
10038
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
8933
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...
0
6712
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
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2850
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.