user1518989
user1518989

Reputation: 25

Allocating Large array(9mb) of pointers in c

I have an Structure defined,

struct RadBuck {
    int size,
    int pos,
    int head
};

I wanted to create an array of this structure as RadBuck *R[n]. Everything is fine if n is small but the moment I reach 9 MB, I am getting segmentation fault. I have the same problem with int a[n] as well, but that I overcame, by mallocing it, int *a = (int*) malloc(n*sizeof(int)); Since that is not possible for struct, I am confused.

Upvotes: 0

Views: 88

Answers (2)

WileTheCoyot
WileTheCoyot

Reputation: 523

When you use malloc or declare an array of size n the compiler try to allocate the needed space as contiguous in the memory. So, if you need a lot of memory, you should try to use a linked list instead of a vector. When you use a linked list your elements are sparse in memory and you should get a lot more. If you want to use a linked list, you can rewrite your structure like this:

struct RadBuck {
    int size;
    int pos;
    int head;
    struct RadBuck *next;
};

Upvotes: 0

alk
alk

Reputation: 70931

Since that is not possible for struct, I am confused.

This surely is possible:

#include <stdlib.h> /* for malloc() */
#include <stdio.h> /* for perror() */

size_t n = 42;

struct RadBuck * p = malloc(n * sizeof(*p)); /* Here one also could do sizeof(struct RadBuck). */
if (NULL == p)
{
  perror("malloc() failed");
}
else
{
   /* Use p here as if it were an array. */
   p[0].size = 1; /* Access the 1st element via index. */

   (p + n - 1)->size = 2; /* Access the last element via the -> operator. */
}

free(p); /* Return the memory. */ 

Btw, it shall be:

struct RadBuck {
  int size;
  int pos;
  int head;
};

Use semicolons (;) to separate the structure's member declarations.

Upvotes: 2

Related Questions