Vector of large size in C

Asked

Viewed 109 times

-1

I’m studying the data types of the C language. And today I decided to create a vector of very large size, in this case, 10 8. So, I made a small code in which I declare this large vector (being that the value 10 8 fits the type Int), fill its positions and try to access a certain element of it. However, the program is not running properly, nothing happens, although no build error is being displayed. Could you tell me the correct way to create such a large vector? Thanks in advance!

#include <stdio.h>

int main() {
  int vet[100000000], i;

  for (i = 0; i < 100000000; i++)
    vet[i] = i;

  printf("%d", vet[200]);

  return 0;
}
  • Here https://ideone.com/8qyNex has run correctly. But it will depend on your environment and available memory.

  • Complementing: take a studied stack and heap to understand the memory allocation and why when using dynamic allocation can escape the stack overflow.

1 answer

0

There is a limit to memory allocation for a process/program, this is valid for any programming language and environment. If you exceed a certain limit, processes in the computer will start to lock due to lack of available memory (this includes processes of the Operating System itself). You’ve probably reached that limit.

You can instead of statically allocating memory to a vector of 100000000 elements (4 bytes x 100000000 = ~400 MB), use the dynamic memory allocation engine of the C language.

How it works: You allocate the memory needed to store one unit of information in the vector at a time. In your case, the unit of information is an int (4 bytes) (disregarding address information and pointers).

You can see more details about this process at this link.

But reinforcing, this will not solve your problem of allocating a vector of this size or larger. For this you will need more available memory.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.