Michał Tabor
Michał Tabor

Reputation: 2467

Questions about dynamic memory allocation in C

  1. What is the difference between

    int size;
    int *arr;
    scanf("%i", &size);
    arr = malloc(size * sizeof(*arr));
    

    and

    int size;
    scanf("%i", &size);
    int arr[size];
    
  2. When I want to allocate memory for 2 big numbers i would use the following code:

        unsigned long *big_nums;
        big_nums = malloc(2 * sizeof(*big_nums));
    

    I would access the first big bumber using big_nums[0] an the seond one with big_nums[1]. Let's say unsigned long is 4 bytes big, then the code would allocate 2 * 4 = 8 bytes. Let's say I do something like this:

        unsigned long *big_nums;
        big_nums = malloc(7);
    

Using big_nums[0] is clear for me, but how about big_nums[1]? Will it cause some kind of segmentation fault error or what?

Upvotes: 4

Views: 521

Answers (3)

Adrian Ratnapala
Adrian Ratnapala

Reputation: 5733

For Q#2: You will be allowed to make that error. And when you write to the second element of the array, you will overwrite one byte that does not "belong" to you.

My guess is that in most cases, nothing bad will happen because malloc(7) will secretly be equivalent to malloc(8). But there is NO GUARANTEE of this. Anything could happen, including a segfault or something worse.

By the way, if you have two separate questions, it would be best to write them up as two separate questions. You get more points way.

Upvotes: 0

Adrian Ratnapala
Adrian Ratnapala

Reputation: 5733

For Q#1: The second version will (try to) allocate a variable-length array on the stack. In C99 onwards, this is possible; but in traditional C variable-length arrays don't exist, and you must roll them yourself using malloc.

Upvotes: 1

woolstar
woolstar

Reputation: 5083

There are two places to get memory from: the stack and the heap. The stack is where you allocate short lived things, and the heap is for allocating long term things.

malloc() allocates from the heap, and int arr[size] allocates from the stack.

When your function exits, arr[size] will be disposed of automatically, but malloc() will not. This leads to what's called "memory leaks".

big_nums = malloc(7);

will indeed be an error if you access big_nums[1]. In general the standard says behavior is "undefined" which means it could work, or might not.

Upvotes: 2

Related Questions