Book I’ve read in 2018

I decided to make this post as a summarize of tech books that I’ve read this year, unfortunately this year I only read six technical books and six misc (that I’ll talk shortly at the end).

All these reviews I posted a book review on goodreads, as I started last month I’ve marked all books as “read” today but I’ve read it during the entire year, you can check my profile at Goodreads here that in 2019 I’ll use this social network on the right way, feels free to follow me.

This year I’ve read different kinds of books, because some books I decided to read because of unexpected needs like, the operating systems books I decided to read because I felt curious at university classes, or that I decided to read “Working effectively with legacy code” to improve my knowledge of legacy code and help more at my work. Let’s start each book review.

99 Bottles of OOP

99 Bottles of OOP Cover

You can check this review at Goodreads here.

I don’t have how to not give a five star to Sandi Metz when talking about OOP. This book is a complete book of OOP and if you make the exercise at the beginning of the book it will blow your mind and increase your experience with the book. It’s a good sequel to Practical Object-Oriented Design in Ruby.

I have a love relationship with Sandi Metz books, and this is not an exception, I recommend this book for all programmers, the quality of the lessons about object oriented programming is unparalleled.

If you can, you can buy it at Sandi personal site, just click here.

The Clean Coder

The Clean Coder Cover

You can check this review at Goodreads here.

Robert C. Martin is very famous for the “Clean Code”, on this book he writes about something like one “code of conduct” that every programmer should follow, and It’s very controversial but for me, it’s normal because is his opinion. I didn’t like the book because the entire book sounds like someone telling you a list of conduct rules that you should follow to be a good programmer, it doesn’t mean that you don’t need to follow any rules described, some rules are good and in my opinion you need to follow them (some of them), but I feel worried if someone read it and start following all these rules as if they were all true without wondering about.

One good thing in this book is the real stories that uncle bob writes almost in the entire book, some stories are very interesting and tell a little about the past and the background of the author.

3 stars.

If you can, you can buy it at Amazon, just click here

Arquitetura de Sistemas Operacionais

Check my last posts:

Arquitetura de Sistemas Operacionais Cover

You can check this review at Goodreads here.

This is a Brazilian book and as you can perceive with the title, it is written in Portuguese, but I’ll make a summary in English.

This book is awesome and the translated title is “Operating Systems architecture”, its not a deeply technical book if you compare with Tanenbaum’s books for example, but it works as expected as a starter kit for operating systems, it has many pictures that can help understand the topics. It is basically a summarize of all operating systems without going deep in any “code”. For me, it was a five stars read.

If you can, you can buy it at Amazon, just click here

The C Programming Language

The C Programming Language

You can check this review at Goodreads here.

The C bible, this book nowadays still relevant and can be a good C book for those who are starting or want to remember to program on C language. I don’t recommend it for beginners, I think that there are good books of C programming for beginners that don’t have any background.

If you can, you can buy it at Amazon, just click here.

Working Effectively with Legacy Code

Working Effectively with Legacy Code

You can check this review at Goodreads here.

This book is famous and I think when it was written, it made a lot more sense than nowadays. In most parts, the book treats legacy code only as the project that doesn’t have tests and spend a lot of time telling you how to make changes in small steps and write tests, unfortunately nowadays many developers deals every day with legacy code that have tests and face other kinds of problems like, libs versions, architecture, technical debts, refactoring and much more (The book talks about some problems that I described here, but not in an up-to-date way), the fact that the code “doesn’t have tests” is not the only thing that classifies it as legacy code anymore.

If you’ll read this book, jump to chapter 14.

If they release the second edition of this book, I’ll buy for sure.

If you can, you can buy it at Amazon, just click here

Automate the Boring Stuff with Python

Automate The Boring Stuff With Python Cover

For those who already follow my activities you already know that I’ve read it, and I already have a full review here, at my blog, if you want to check the full review click here

You can check this review at Goodreads here.

5 stars for beginners.

3 stars for programmers who already know how to program in another interpreted programming language like Ruby.

TL;DR: It’s a book recommended for novices, for me, it’s a good book for beginners, but for people who already know how to program in other dynamic and interpreted programming language, I think is not necessary to read this book, go ahead an read something more advanced.

The book is divided into two parts, the first one talks about all the basic things of any programming language like variables, loops, ifs/else and etc. This part is good to understand the basic of python. This part covers all between variables and manipulates text.

The most interesting is the second part when you create a lot of applications to automate boring stuff, but the first part is good to understand and knows the python basic. One thing that I loved on this book is the fact that it has a lot of exercises (with answers) to you train what you learned on the chapter, if you do all the exercises your read will be funnier and you’ll learn much more.

Conclusion: The only bad thing on this book is that this is a simple book for people that already know how to program, but this is not a problem because the book doesn’t say that is something advanced, but even for who already knows how to program, the second part with practical projects can be very good.

If you can, you can buy it at Amazon, just click here

How to Win Friends and Influence People

This is the only non-technical book that I’ll talk about on this post because for me it makes sense and I’ll be short.

How to Win Friends and Influence People Cover

You can check this review at Goodreads here.

A good and classic book of how to deal with people and leadership. The book shows you a lot of real examples and histories, with some obvious things and some not so obvious.

If you can, you can buy it at Amazon, just click here

What’s next?

My focus on 2019 first semester will be compilers and programming languages design, I already bought some books and start reading, I think I’ll make great posts about compilers 🙂

Final thought

If you have any question that I can help you, please ask! Send an email (otaviopvaladares@gmail.com), pm me on my Twitter or comment on this post!

Follow my blog to get notified every new post:

Types of storage on AWS S3

Amazon web services aka AWS provides a few ways of storing your files using the popular service S3(Simple Storage Service), the most common is the called S3 Standard that I think most people use on a normal day to day workflow, another common storage class is the famous S3 Glacier, but I don’t think most people know what is Standard-IA storage class, or One Zone-IA, in this post I want to write about each one and its uses cases.

It’s important to emphasize that this post is dated December 2018 and AWS is constantly changing and adding new features and probably, storage classes, if this post is outdated, please comment or check at my blog if you find a newer one.

All prices will be based on us-east-1 region.

Amazon S3 Standard

This is the default storage class, it’s designed for frequently accessed data, you can use this class for many things that will be accessed frequently, like, images that your user uploads on your website to use as profile image, or high-usage spreadsheets, other use cases can be: cloud applications, dynamic websites, content distribution, mobile and gaming applications, and big data analytics.

Key Features

As the aws official website say, this is the key features of standard class:

  • Low latency and high throughput performance (This is why it’s very recommended for high-usage data)
  • Designed for durability of 99.999999999% of objects across multiple Availability Zones (If you have 100 billion objects, Amazon ensures that you lost only one a year)
  • Resilient against events that impact an entire Availability Zone
  • Designed for 99.99% availability over a given year (Almost 52m 26s downtime per year)
  • Backed with the Amazon S3 Service Level Agreement for availability
  • Supports SSL for data in transit and encryption of data at rest
  • S3 Lifecycle management for automatic migration of objects to other S3 Storage Classes

Pricing

Like almost all services provided, S3 has a long table of pricing separated by store amount, requests, data transfer, management, and transfer acceleration. You can check the full table here.

The S3 Standard Storage is the cheaper storage class when talking about request pricing and this is the main reason why you should use default S3 storage when you’re working with heavy access, you pay a nice price like $0.0004 per 1.000 GET requests.

At the end of the text I’ll make a better comparison between each type and pricing.

Amazon S3 Standard-Infrequent Access (S3 Standard-IA)

Check my last posts:

S3 Standard-IA is for data that is accessed less frequently, but when required needs fast access. You have the minimum storage period of 30 days and a minimum object size of 128KB. It is recommended for backups or logs(depending on the size of your logs, of course!).

Summarizing: All data that will not be accessed once a month and when required needs to be recovered just in time, you use S3 Standard-IA. Obviously, the problem is that you need to know previously the access pattern of your object, but as we’ll see later, this problem is already solved by Amazon S3 Intelligent-Tiering.

Key Features

  • Same low latency and high throughput performance of S3 Standard
  • Designed for durability of 99.999999999% of objects across multiple Availability Zones
  • Resilient against events that impact an entire Availability Zone
  • Data is resilient in the event of one entire Availability Zone destruction
  • Designed for 99.9% availability over a given year
  • Backed with the Amazon S3 Service Level Agreement for availability
  • Supports SSL for data in transit and encryption of data at rest
  • S3 Lifecycle management for automatic migration of objects to other S3 Storage Classes

Pricing

The key point about pricing of S3 Standard-IA is that: Storage is cheap if you compare S3 standard, but a request is expensive.

Storage Price
All storage / Month $0.0125 per GB

Requests Price
Data Retrievals $0.01 per GB
Data Returned by S3 Select $0.01 per GB
Data Scanned by S3 Select $0.01 per GB
PUT, COPY, POST or LIST Request $0.01 per 1,000 requests
GET, SELECT and all other requests $0.001 per 1,000 requests

Amazon S3 One Zone-Infrequent Access (S3 One Zone-IA)

This is the younger brother of S3 Standard-IA and is almost the same service, the difference is that it stores your data at only one AZ (Availability Zone), unlike other S3 storage classes which store data in a minimum of three. With this trade-off, it costs 20% less than its older brother. It’s ideal for customers who want a lower-cost option for infrequently accesses data.

Key Features

The key features are the same as S3 Standard-IA, with the difference in the availability of 99.5% (Compared with 99.9% of Standard-IA).

Princing

The request price is the same as Standard-IA, and the storage price is 20% cheaper.

Storage Price
All storage / Month $0.01 per GB

Amazon S3 Intelligent-Tiering

This is the most interesting and newer one, it was released at November 2018, we saw that for high-usage files is better to use S3 Standard and to infrequent access data use Standard-IA, this is nice but we have one problem that some users already know, what we do if we don’t know the access pattern of the object? or if we don’t feel confident to change one object of the standard to Standard-IA?

Now imagine if Amazon creates something to do that for you? And they did it, and the problem has gone, this creation is the new Amazon S3 Intelligent-Tiering, it is designed for who want to optimize storage costs automatically when data access patterns change or you don’t know it.

It works with two objects tiers, one tier is similar do S3 Standard and another tier that is similar to Standard-IA, all object, when uploaded, is moved to the first tier that is for frequent access data, if the object has not been accessed for 30 consecutive days, Amazon moves it to the second tier that is for infrequent access data. Amazing, isn’t it?

Objects smaller than 128KB will never be transitioned to the infrequent access tier.

It’s important to point that we don’t have retrieval fees on this storage class.

Key Features

Follow my blog to get notified every new post:

  • Same low latency and high throughput performance of S3 Standard
  • Small monthly monitoring and auto-tiering fee
  • Automatically moves objects between two access tiers based on changing access patterns
  • Designed for durability of 99.999999999% of objects across multiple Availability Zones
  • Resilient against events that impact an entire Availability Zone
  • Designed for 99.9% availability over a given year
  • Backed with the Amazon S3 Service Level Agreement for availability
  • Supports SSL for data in transit and encryption of data at rest
  • S3 Lifecycle management for automatic migration of objects to other S3 Storage Classes

As you can see the key features are almost the same, except for the 99.9% availability (comparing with 99.99% of standard S3) and the feature of automatically moves the object between access tiers.

Princing

The price is awesome too when talking about storage pricing we have the same price of standard storage on frequent access tier, and the same price of Standard-IA to infrequent access tier.

Storage Price
Frequent Access Tier
————- —————
First 50 TB $0.023 per GB
Next 450 TB $0.022 per GB
Over 500 TB $0.021 per GB
————- —————
Frequent Access Tier
————- —————
All storage $0.0025 per 1,000 objects

For requests, we have the same price as the standard tier.

Requests Price
Data Returned by S3 Select $0.0007 per GB
Data Scanned by S3 Select $0.002 per GB
PUT, COPY, POST or LIST Request $0.0005 per 1,000 requests
GET, SELECT and all other requests $0.0004 per 1,000 requests

S3 Glacier

Glacier is designed to data archive if you have some data that you think you’ll never need again and if needed you can wait for almost 5 hours of the recovery process, go ahead and use Glacier, the price of the storage is the cheaper of the S3 classes. Example of things to store on S3 Glacier: Old logs that you can’t delete, old database dumps or your wedding pictures(just kidding but is a great idea).

One common action when working with Glacier is to setup a lifecycle policy to archive on Glacier data from S3 Standard bucket after n time, for example, 360 days, this is an amazing feature and provides a nice power to you.

Key Features

  • Designed for durability of 99.999999999% of objects across multiple Availability Zones
  • Data is resilient in the event of one entire Availability Zone destruction
  • Supports SSL for data in transit and encryption of data at rest
  • The low-cost design is ideal for long-term archive
  • Configurable retrieval times, from minutes to hours
  • S3 PUT API for direct uploads to S3 Glacier and S3 Lifecycle management for automatic migration of objects

Pricing

Amazon S3 Glacier has an extremely low cost of storage, cheaper than all other services that we studied.

Storage Price
All storage / Month $0.004 per GB

AWS provides three retrieval options, Expedited, Standard, Bulk, that range from a few minutes to hours and obviously from the cheapest to the most expensive one.

Expedited Standard Bulk
Retrieval Time 1-5 Minutes 3-5 hours
Data Retrievals $0.03 / GB $0.01 / GB
Retrievals Requests $0.01 / Request $0.050 / 1k Request

Conclusion

All storage class has its specific case of use, choose one used to be a problem when you don’t know the access pattern of the object, but today with S3 Intelligent-Tiering isn’t any more you can enable it and Amazon take a care for you, if add a lifecycle police to archive data from this bucket to Glacier after some time, you are with an amazing solution at your hands.

If you know the access pattern, just choose the better to your case and use it, S3 is amazing and cheap!

Final Thought

If you have any question that I can help you, please ask! Send an email (otaviopvaladares@gmail.com), pm me on my Twitter or comment on this post!

Links

Types of Memory Allocation, a brief view

A few months ago, I started a series of posts about important topics of C programming and computer architecture, the first post was about pointers and you can check here, on this post I’ll talk about types of memory allocation.

I’ve many criticisms about some ways that people usually teach C programming, one of these is that is very difficult to find someone that explains the difference between each type of variable and allocation, they usually only say “that is a variable and use it” or “look, this is a malloc(), start using it”, on this text I’ll try to show the difference between each type, for those who didn’t learn it learn and for those who learned it remember it!

This is a topic that I see few authors writing about, and I think few people have learned about this while studying C programming, on this post(and on the next talking about C memory layout), I hope I help people understand better this part of computer programs.

Types of Allocation

Follow my blog to get notified every new post:

Automatic Memory Allocation

How to use

Automatic memory allocation corresponds to the automatic variables, also known as “stack” memory, it’s memory allocated at runtime when you enter into a new scope, each time that a function is called it’s auto variables are pushed to the stack.

Worried because you don’t know what is the stack, don’t panic, this will be explained on the next post.

What it really means? An auto variable is every variable that you declare and doesn’t use any keyword (like static), simplifying, variables that you declare inside your main function or inside any function can be considered auto variables, therefore, automatic memory allocation.

#include <stdio.h>


int main() {
    int a = 1;
    int b = 2;

    printf("Sum: %d", a+b);

    return 0;
}

In the previous example, both variables a and b are auto variables. It’s important to remember that in C you have the keyword auto to specify this kind of variable, but by default every variable inside a block/scope it’s an auto variable, so you don’t need to use this keyword.

This example is the same as the previous:

#include <stdio.h>


int main() {
    auto int a = 1;
    auto int b = 2;

    printf("Sum: %d", a+b);

    return 0;
}

Variables declared inside scopes are auto too:

if (a < b) {
    int c = 10;
}

The lifetime of automatic variables is only during the execution of its scope/block when the function/block is called the variable is pushed to the stack and start your life, after the end of the function/block it is popped off of the stack and doesn’t exist anymore.

void anyThing() {
    int autoVariable = 10;

    autoVariable += 10;
}

int main() {
    anyThing();
    /* The variable autoVariable doesn't existis here */
    /* it only exists inside its function*/

    return 0;
}

It can look obvious to the majority of programmers but I think that few ask themselves about why it occurs.

Summarize

Every variable declared without any keyword(or auto keyword) at any function will be considered “auto” variables, and will be automatically allocated during runtime of the software at memory using the program’s stack, this kind of variable lifetime is only during the execution of the function block or scope, after this, the variable is pushed out of the stack.

Static Memory Allocation

Static variables are another type of variables and memory allocation, the major difference is that they preserve its value, they aren’t created/destroyed each time that your program calls a function. It corresponds to file scope variables and local static variables, their lifetime is the lifetime of the program.

How to use

To declare a static variable, the only thing that you need to do is to use static keyword, as the following example:

static int age = 18;

This characteristic can be used to do interesting things, the variable is not destroyed when your software get out of the scope, so you can use it to count how many times one function is called, this is the most popular example of static variables:

#include <stdio.h>


void count() {
    static int counter = 0;
    counter++;
    printf("Counter = %d\n", counter);
}

int main() {
    count();
    count();
    count();
    count();

    return 0;
}

The scope of a static variable is the scope of the function, the only difference is that they aren’t destroyed on the final of the function call, if you try to access a static variable outside of its scope you’ll get a compilation error.

They are allocated on compile time that fixes their addresses and sizes (so, the executable of the software already have the location and size of these variables), the name “static” is because they do not vary in location or size during the lifetime of the program (because the compiler already fixed it at executable).

It’s important to know that they aren’t stored at stack like automatic allocation, or at the heap (like the dynamic allocation that we’ll see below), this kind of variable is stored in the data segment of the programs address space if they are initialized or the BSS segment if they aren’t initialized.

Worried because you don’t know what is BSS/Data Segment/Stack/Heap? Don’t panic, this will be explained on the next post.

The compiler fixes the address and size of the static variable at compile time, so a static variable can only be initialized using constant literals, because the compiler needs to know the value of the variable, you can’t initialize a static variable with a returned value of a function for example, the following program will generate a compile error:

#include <stdio.h>


int initializer(void) {
    return 50;
}

int main() {
    static int i = initializer();
    printf(" value of i = %d", i);
    getchar();

    return 0;
}

Some people can think that static variables and global variables are the same things, but they aren’t, they have different scopes, you can’t access static variable of one function int count() inside the function int sum(), while the global variable can be accessed in any function. But some question may appear, like, if we put a static variable on the global scope, it will be the same as a global variable? and the answer is no. Let’s take a look:

#include <stdio.h>


static int counter x;
int counter y;

int main () {
  // anything
}

On this example, we have two global scoped variables but the x is of the static type, now you can ask me, what’s the difference? x will have static linkage (file scope), the variable is only accessible in the current file, while the y has an external linkage and you can refer to this variable if you declare it with extern in another file, both variables follow the same rules to be stored (as I described before).

Summarize

Static variables are statically allocated and their size and addresses are fixed at compile time, the major difference is that it preserves its value, they aren’t created/destroyed each time that your program calls a function, they have function scope and are stored at data/BSS segment.

Dynamic Memory Allocation

The famous dynamic memory(aka DMA) allocation that scares a bunch of people at the college, it isn’t brain surgery and I’ll prove to you, dynamic memory allocation can be very interesting and fun if you really understand it from the beginning.

Reinforcing the importance of pointers to dynamic memory allocation, I suggest that you have a solid knowledge of pointers, you can read any tutorial on the internet, or the one that I have here, on my blog.

Different from previous examples, dynamic memory is allocated on the heap, that I’ll explain in details on next post.

To dynamically allocate memory in C language(this part its different from C++), you need to include stdlib.h to have access to functions that C provides to dynamic allocation, you can check all functions that you’ll gain access here but on this post, we’ll only take a look at only four of them:

void *malloc(size_t size);
void free(void *ptr);
void *calloc(size_t nmemb, size_t size);
void *realloc(void *ptr, size_t size);

malloc()

Check my last posts:

Let’s start with void *malloc(size_t size) probably one of the most famous functions of computer science. It allocates n bytes of memory and returns as a pointer, it’s important to be careful because n needs to be the exact number of bytes that you need to store your data, for example, if we want to store simple information of the type int as we remember we’ll need 8 bytes, so, you pass 4 to the malloc() and it’ll return a pointer to the first byte of this block of memory:

int *number = malloc(4);

Now your variable number is a pointer to a block of 4 bits of memory, the necessary to store an integer:

#include <stdio.h>

#include <stdlib.h>


int main () {
    int *number = malloc(4);

    *number = 1234;

    printf("%d", *number);
}

If you try to store a number that has more than 4 bits you’ll get an overflow error.

You probably are asking yourself if you’ll need to know the size of each data that you’ll store, and fortunately, the answer is no, you don’t have to know all the data size, we have a function that returns the data size and is called sizeof(), to use it is very simple, just pass the variable type(or a variable of the type) that you want. Combining it with the previous malloc() you’ll have great power in your hands.

#include <stdio.h>

#include <stdlib.h>


int main () {
    int *number = malloc(sizeof(int));

    *number = 1234;

    printf("%d", *number);
}

If you need to create an array dynamically just multiply the size by the number of items of your array, for example, if you want an array of 10 ints, just do that:

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

free()

Another important function from stdlib.h is free(), it’s so important to your memory management and if you forgot to use free() you’ll have a memory leak. Simplifying, C programming language doesn’t have a garbage collector, it means that all memory that is dynamically allocated don’t get destroyed by the language in runtime, and you need to manage memory use by yourself while coding if you allocate a new memory using malloc() when you stop using this variable you SHOULD free it.

#include <stdio.h>

#include <stdlib.h>


int main () {
    int *numbers = malloc(sizeof(int) * 10);

    for(int i = 0; i < 10; i++) {
        numbers[i] = i + 10;
        printf("%d\n", numbers[i]);
    }


    free(numbers);
}

calloc() and realloc()

We have also two more functions to discuss here, calloc() and realloc(), they are very simple if you understand the concept of malloc() let’s start with calloc().

calloc() is equal to malloc() with two differences: calloc() it initializes all values of your block with 0 while malloc() initializes each block with garbage values, and it takes two arguments, the number of blocks to be allocated and size of each block, with this, if you want to allocate an array of 10 ints, you don’t need to multiply 10 by the size of each block, you just need to pass ten as argument.

int *numbers = calloc(10, sizeof(int));

realloc() as the name says you can re-allocate a memory previously allocated using in other words, if you have an array previously allocated with 5 ints using malloc() and you want to resize it to 10 ints, you can use realloc(). To use it, you only need to pass the previous pointer and the new size. Using it, you’ll resize the allocated space on the heap.

int *numbers = malloc(sizeof(int)* 5);

int *newNumbers = realloc(numbers, sizeof(int)* 10);

I’ll not enter in details of how to use malloc(), realloc(), calloc() and free because isn’t the objective of the text, on a future post I’ll only write about how to use this functions with mastery.

Why use DMA?

Follow my blog to get notified every new post:

I think one of the most common doubts among students is “Why did I need to use dynamic memory allocation, I don’t need it!!” or something like “Why did I need another way of creating variables?”. The most common case to use dynamic memory allocation is when you don’t know the input on compile-time and need to manage memory at runtime of the program, what it means? For example, you have to store n integers from the user’s input and you don’t know how many integers the user will store on the compile-time, in this case, you have three ways…

You can create a large array of integers as in the following example we use int numbers[500], the trade-off of this way is that if your user store less than 500 numbers you have a memory leak, because a smaller array would be better, and if your user wants to store more than 500 numbers your software wouldn’t support it.

#include <stdio.h>


int main() {
    int numbers[500];
    int counter;

    printf("How many numbers you will store? ");
    scanf("%d", &counter);

    for(int i = 0; i < counter; i++) {
        printf("Enter with number %d: ", i+1);
        scanf("%d", &numbers[i]);
    }

    /* any logic .. */

    return 0;
}

The other way is to use variable-length arrays (also called VLA), this solution is very close to the previous, the only difference is the use of VLA when creating the array.

#include <stdio.h>


int main() {
    int counter;

    printf("How many numbers you will store? ");
    scanf("%d", &counter);

    int numbers[counter];

    for(int i = 0; i < counter; i++) {
        printf("Enter with number %d: ", i+1);
        scanf("%d", &numbers[i]);
    }

    /* any logic .. */

    return 0;
}

It partially solves our problem, we won’t waste memory but use VLA is controversial and if you search on the internet (and I encourage you to search) you’ll find a lot of people talking about why you shouldn’t use VLAs. But we have two main problems with this solution, the first is that our array will be automatically allocated, it means that it will be allocated on stack memory, this is a problem because stack memory is not a large memory and if you try to allocate a large array you’ll get stackoverflow error, other problem, as you know, is that automatic variables only exist on the current scope. Another small problem with this solution is that VLA was introduced on C99 and old compilers will not compile it.

The other solution is to use dynamic memory allocation with malloc() to reserve a block of memory with the exact size that we need, this is the best solution is almost all cases:

#include <stdio.h>

#include <stdlib.h>


int main() {
    int counter;

    printf("How many numbers you will store? ");
    scanf("%d", &counter);

    int *numbers = malloc(sizeof(int) * counter);

    for(int i = 0; i < counter; i++) {
        printf("Enter with number %d: ", i+1);
        scanf("%d", &numbers[i]);
    }

    /* any logic .. */

    free(numbers);
    return 0;
}

This is the best solution and it’s using DMA in the right way, you’re using heap memory and you have full control of when you want to free this block of memory using free(), another good thing is that you can use realloc() if you want to resize our block.

Summarize

The necessity of dynamically allocated memory is a reality on everyday programmers day, you’ll need to know how to use malloc() to allocate heap memory at runtime, the advantages are many, you have full control of your memory, you choose when you want to free this memory, and you gain control over memory usage of your software.

Conclusion

Understand the difference between each type of memory allocation is good to understand correctly how your C software works under a microscope, on this post we discussed about each type and on next post we’ll talk about memory layout of C programs, with both knowledge, you’ll have a complete understanding of this part of C software and will write and understand your software better.

Unfortunately, this is a part of programming that I see few authors writing about, on this post and on the next I hope I can help people understand the software better.

Final thought

If you have any questions that I can help you with, please ask! Send an email (otaviopvaladares@gmail.com), pm me on my Twitter or comment on this post!

Links

Misc

What’s the overhead of using VLAs

How to use VLAs

C data types

Dynamic, static and automatic memory

Difference between automatic, static and dynamic variable

Types of variables

Dynamic memory allocation

Wikpedia of dynamic memory allocation
What is dynamic memory allocation
C dynamic memory allocation
Differente between static and dynamic memory allocation
C function malloc
stdlib.h
Nice guide about malloc

Static memory allocation

Static memory allocation
Static variables in C
Wikipedia page of Static variable
Difference between global and static global
Difference between the global and static variable in C
Static vs Global variables
Difference between the global and static variable in C
Local global and static variable

Follow my blog to get notified every new post: