Introduction

Hey! Guyz.. Welcome to my very short tutorial explaining basic uses of "malloc" function in C language.

[NOTE : You need simple understanding about pointers to understand this tutorial]

Hey guyz see by reading this tutorial you'll not be a malloc expert ..

This tutorial is only for the very Basics..

So what are we waiting for lets get started..

About Malloc

Malloc() is a very powerfull function in C language. It is used in almost every powerful program or the any program which deals with pointers.

According to my understanding the best way to learn something in C is by example code so:-

#include<stdio.h>     /* For standard input output */
#include<malloc.h>    /* You need this if on UNIX or LINUX */
#include<string.h>

int main()
{
    char words[]={"Hey this is a simple tutorial on malloc\n"};
    char *p;    /* char pointer for use with malloc() */

    p = (char *)malloc(sizeof(words)); /* Explained in the following text */

    strcpy(p,words);

    printf("p = %s\n",p);
    printf("words = %s\n",words);

    return(0);
}

[mark=code]The Code[/mark]

Explanation:-

lines 1-3:-
include files needed

lines 7-8
Declarations already explained in comments.

line 10 /* the real stuff */Here come malloc():-

*************************************************************

first something about malloc :-


The prototype of malloc is as follows:-

void *malloc(size_t size);

malloc();
takes one argument as an input that is number of bytes to be "allocated" in memory as simple as that.

But hey what is that weird looking statement before malloc(); ..
That is called cast.

If you have read about cast in C you would be having no problem in understanding this .
But if not read about this now "Hey but after reading this tutorial".

**************************************************************

Something about sizeof();
prototype:-

sizeof(data);

1. You must be thinking what is that sizeof(words) in the "arg" of malloc.
2. The sizeof() takes input of data and returns an integer value that is number of bytes that data is .
eg:-
char = 1 bytes.
int = 4 bytes.
etc.
3. In this case it is the sizeof(words) here words is an array and the number of characters in 40 and now how many bytes we need
40 * 1;
because character is 1 byte and words contains 40 characters.

4. sizeof() ; function says it all . It means size of the "data" in this case "words".

You must be thinking where he is getting us with all this stuff .. but these were important.

***************************************************************

Ok now let's get to the output of the program.

Output :-

p = Hey this is a simple tutorial on malloc.
words = Hey this is a simple tutorial on malloc.

As expected.

Yeah! Guys you'll be thinking that what is the use of this function.
As you get into some experienced programming you'll get answer of that ..

as I said this function is very powerful and is very advanced it is basically used in linked lists and and some "structs I guess "

But i'd not touching that topic ..
Now you all have simple understanding of malloc().. "Say Yess "

References

No references guyz ... Only one my "brain" .. LOL..

[mark=ref]Contact me[/mark]

For reporting any errors or questions contact me on :-

SNIP

Further reading

Sizeof: http://www.ncl.ucar.edu/Document/Functions/Built-in/sizeof.shtml
Malloc: http://en.wikipedia.org/wiki/Malloc
Linked Lists : http://www.codeproject.com/KB/cpp/linked_list.aspx

jephthah commented: inaccurate and misleading. since you labeled this as a "TUTORIAL" demands a negative score. -1

Recommended Answers

All 11 Replies

> #include<malloc.h> /* You need this if on UNIX or LINUX */
This is all wrong.
malloc is prototyped in stdlib.h

> p = (char *)malloc(sizeof(words));
You don't need to cast malloc in C programs.

Have you tried it without the cast? Did you get any error messages?

These perhaps?
"implicit conversion of int to char*" -> you didn't include stdlib.h
"conversion of void* to char*" -> you're using a C++ compiler to compile C code.

> 4. sizeof() ; function says it all . It means size of the "data" in this case "words".
sizeof is an operator, not a function.
Passing an array to a function yields a pointer to the first element of that array.

The parentheses are optional when applying sizeof to a variable.
p = malloc(sizeof words );

Other issues:
- you didn't check malloc for success
- you didn't describe free(), the essential complement to using malloc.

The parentheses are optional when applying sizeof to a variable.
p = malloc(sizeof words );

Now I didn't know that. I guess that's why I keep coming back.

Now I didn't know that. I guess that's why I keep coming back.

sizeof is an unary operator and not a function, the parenthesis are only necessary for precedence sake.

[Edit:]
Missed this point from Salem

> 4. sizeof() ; function says it all . It means size of the "data" in this case "words".
sizeof is an operator, not a function.

Which makes my comment redundant and unnecessary.


lionaneesh>Sizeof: http://www.ncl.ucar.edu/Document/Functions/Built-in/sizeof.shtml
That links to a page explaining a function for NCL programming language, and not ANSI C

Guyz :( you should understand that i am a human and i can be mistakened OK!

So, please don't post bad reputation points.

You all should understand that atleast I tried to write a tutorial.

Man are you all guyz perfect .. HUH! :(

Based on your reply, I take that you are seeing too much red at the moment. But anyhow, I'd suggest that you get over that, and instead go through the replies you received, improving your tutorial. After all, that's the purpose of these replies, don't you think so too?

PS. Also note that your post could have been completely ignored, but it wasn't.

commented: Absolutely. +8

Based on your reply, I take that you are seeing too much red at the moment. But anyhow, I'd suggest that you get over that, and instead go through the replies you received, improving your tutorial. After all, that's the purpose of these replies, don't you think so too?

PS. Also note that your post could have been completely ignored, but it wasn't.

Thnx for motivating ...
Thnx a lot...

char words[]={"Hey this is a simple tutorial on malloc\n"};

i think it shoud end with \0 or nothing is required over there

i think it shoud end with \0 or nothing is required over there

Not necessary -- the compiler will generate the '\0' null terminator. But the { and } characters are unnecessary.

Guyz :( you should understand that i am a human and i can be mistakened OK!

So, please don't post bad reputation points.

You all should understand that atleast I tried to write a tutorial.

Man are you all guyz perfect .. HUH! :(

when you post something and declare it is a "tutorial" then, yes, you are holding your code up to be critiqued to standards of perfection.

notice how many tutorials there currently are for C. There is one (1). that's it. now maybe there should be more, and certainly there could be more, but before you are going to add one then you better make sure your code and explanations are rock-solid and dead-on before you hit that "submit" button.

especially with something as critical as malloc(). improper/sloppy use of malloc() is the source of very many problems in programs because people don't fully understand how to use it correctly. it doesnt help matters when people who don't fully understand how to use it correctly, go and declare their half-formed ideas as "tutorials" on a search-optimized programming forum that will propagate misinformation for years to come.

had you just posted this as a question or an example -- i.e., if you had left "tutorial" out of the subject -- you wouldn't have been downvoted.

when you're really an authority on a subject, you will cite credible references, not "just your brain". at that point, you might be ready to write a tutorial.

i think it shoud end with \0 or nothing is required over there

When we use (")and(") operators {Double quotes}..
the compiler automatically sets up \0 "NULL" at the end.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.