Merna George
Merna George

Reputation: 19

Using Malloc for variables

So my professor spent 5 minutes on Malloc, and now we have to use it in a project, but I'm really confused. We're supposed to allocate memory for an array. I know Malloc allocates memory then it returns a pointer to the first byte. How do I use that in a variable? Can I assign a variable to a pointer? Here's what I have so far:

char *ptr;
ptr=((char*) malloc(10*sizeof(char));

I think this is accurate, but I don't know where to go from here. If I declare my array, wouldn't that automatically create a space for it? can I move it to the malloc space? I'm just not sure how this works.

Upvotes: 0

Views: 1835

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311186

Let's start from a demonstrative program.

Here you are.

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

int main(void) 
{
    size_t n = 14;

    char *s = malloc( n );

    if ( s != NULL )
    {
        strcpy( s, "Hello World!" );

        puts( s );
    }

    free( s );

    return 0;
}

The program output is

Hello World!

So in this declaration

char *s = malloc( n );

there was allocated enough memory to store the string literal "Hello World!". However the system can have no enough memory. In this case the returned by the function malloc value of the pointer will be equal to NULL.

So before using the allocated memory we are checking whether the memory was allocated successfully.

if ( s != NULL )

If so then we may copy the string literal "Hello World!" to the allocated memory.

strcpy( s, "Hello World!" );

Usually beginners make an error. Instead of coping a string literal (or some other string) in the allocated memory they just write

s = "Hello World!";

After this assignment the address of the allocated memory is lost and the pointer s points now to the memory occupied by the string literal instead of the allocated memory. As a result there is a memory leak.

When we not need the object stored in the allocated memory the memory must be freed.

free( s );

That is all at the first time.

In general when you are allocating a memory for an array of N elements that have the type T (where T is an arbitrary type) then you need to write

T *p = malloc( N * sizeof( T ) );

For example if you want to allocate an array of 10 integers you should write

int *p = malloc( 10 * sizeof( int ) );

sizeof( char ) is always equal to 1. So in the demonstrative program above I wrote

char *s = malloc( n );

because it is the same as

char *s = malloc( n * sizeof( char ) );

Also in C it is unnecessary to cast the returned value of malloc like

T *p = ( T * )malloc( N * sizeof( T ) );

because the function malloc returns a pointer of the type void * that can be implicitly converted to pointer to object of any other type. You can use casting for self-documenting your code.

Opposite to C in C++ there is no such implicit conversion. So in C++ you have to use casting

T *p = ( T * )malloc( N * sizeof( T ) );

Upvotes: 1

Dejan
Dejan

Reputation: 113

I'm assuming you have basic knowledge of pointers, so this is an example of how to use a char array (aka. a C string).

char *str = (char*)malloc(sizeof(char)*YOUR_ARRAY_SIZE);

str[0] or str[i] in a loop is how you access specific elements. This way you can acheive a user defined size of your array. What i mean is the user can input an integer value, let's call it n. So you can say:

char *str = (char*)malloc(sizeof(char)*n);

Some links that can help you better understand malloc:

https://www.tutorialspoint.com/c_standard_library/c_function_malloc.htm

https://www.programiz.com/c-programming/c-dynamic-memory-allocation

Upvotes: 0

Related Questions