olfek
olfek

Reputation: 3520

Array of pointers - need bigger

How can I create an array of pointers that can store more than 1,047,141 pointers? I calculated this number using the following code:

int main(int argc, char const *argv[]) {
  long a = 0;
  while(1==1){
    char * str[a];
    printf("%ld is good.\n", a);
    a++;
    //Loop ends on Segmentation fault
  }

  return 0;
}

I am using the array of pointers to store strings. What are the alternatives?

Edit

The code above is just a way of finding the max size of an array of pointers.

One pointer holds one string, so the max number of strings I can store is 1,047,141. I need a way of storing more than 1,047,141 strings.

Upvotes: 0

Views: 111

Answers (3)

evaitl
evaitl

Reputation: 1395

The OP code has undefined behavior. The array isn't used, so if you use -O2 (gcc), you are just printing a as it increments. Gcc generates:

.L2:
    movq    %rbx, %rdx
    movl    $.LC0, %esi
    movl    $1, %edi
    xorl    %eax, %eax
    addq    $1, %rbx
    call    __printf_chk
    jmp .L2

It won't segfault, but the output will be quite boring.

However, with -O0, gcc generates a much longer loop (that I don't want to paste) that creates larger and larger str buffers on the stack. At some point when running this you will run out of stack space, which can cause a segfault.

Upvotes: 0

FedeWar
FedeWar

Reputation: 547

You have to allocate the arrays on the heap with malloc. This code will allocate an array of pointers long how_many_strings; and for each pointer it will allocate a string long str_length.

char** str = malloc(sizeof(char*)*how_many_strings);
for(int i = 0; i < how_many_strings; i++)
{
    str[i] = malloc(sizeof(char)*str_length);
}

The size is limited to your RAM capacity.

Upvotes: 2

MikeCAT
MikeCAT

Reputation: 75062

Allocate the array dynamically via malloc().

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[]) {
  long a = 0;
  while(1==1){
    char ** str = malloc(sizeof(char*) * a);
    if (str != NULL){
      printf("%ld is good.\n", a);
      free(str);
    } else {
      break;
    }
    a++;
  }

  return 0;
}

Upvotes: 4

Related Questions