0

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.

Vlad from Moscow
  • 224,104
  • 15
  • 141
  • 268
  • Did you do any research? Fire up your favourite search engine and punch in "C malloc array". That would provide you alot of info. The code shown is not correct. It needs to be `char *ptr;`. And drop the cast as that is not needed/desired in C. – kaylum Apr 18 '20 at 22:33

2 Answers2

1

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 ) );
Vlad from Moscow
  • 224,104
  • 15
  • 141
  • 268
0

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

Dejan
  • 103
  • 1
  • 9
  • 3
    [Do I cast the result of malloc?](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Arkadiusz Drabczyk Apr 18 '20 at 22:35
  • @ArkadiuszDrabczyk nowadays when the compilers emit the warnings about missing function prototypes that link is a bit outdated (I would say 10y+). Now it does not harm. – 0___________ Apr 18 '20 at 22:41
  • It's just one of the arguments and warnings can be missed in a huge project, can be ignored by developers, compilers may have bugs. – Arkadiusz Drabczyk Apr 18 '20 at 22:44
  • 1
    @P__J__ It's does harm in that it's unnecessary, so it reduces code readability and slightly increases the maintenance burden. – jamesdlin Apr 18 '20 at 22:49
  • @ArkadiuszDrabczyk It's highly unlikely to find a compiler bug, and if the compiler gives you a warning you'd do best to address it. Leave a list of warnings that "could" be ignored and a more serious one can get lost in the mix. – dbush Apr 18 '20 at 22:59
  • @dbush: I know that well but not everyone does, following good practices recommended by more experienced developers might help them save a lot of trouble. `it's highly unlikely to find a compiler bug` - I beg to differ, there are quite many bugs in each huge project https://gcc.gnu.org/bugzilla/buglist.cgi?chfield=%5BBug%20creation%5D&chfieldfrom=7d – Arkadiusz Drabczyk Apr 18 '20 at 23:02
  • @ArkadiuszDrabczyk what warning can be missed? Please give me an example. – 0___________ Apr 18 '20 at 23:07
  • @ArkadiuszDrabczyk did you go through those "serious" errors? (it is a rhetoric question as I know the answer) – 0___________ Apr 18 '20 at 23:09
  • @P__J__: *any* warning can be missed if you never look at build output and don't use `-Werror`, it's especially easy if you build a large project or when it's composed of multiple steps like build, test, test, test and you cannot even see the output printed by compiler because you cannot scroll that much. – Arkadiusz Drabczyk Apr 18 '20 at 23:11
  • @P__J__: you know, whatever, if you have some thoughts about casting result of `malloc()` you can share them in the post I linked to if you haven't already. – Arkadiusz Drabczyk Apr 18 '20 at 23:11
  • @ArkadiuszDrabczyk focus on the **topic** . Answer the question. What warnings can be missed if you cast the result of **malloc**? Examples. Even if you use any possible warning command lone options. – 0___________ Apr 18 '20 at 23:41
  • @jamesdlin it is question of the preference. Preferences are opinion based and considered off-topic here as I remember – 0___________ Apr 18 '20 at 23:46