Increase the maximum size of char array

10,021

You can allocate the array dynamically:

#include <stdlib.h>
char *a = malloc(100*sizeof(char));
if (a == NULL)
{
 // error handling
 printf("The allocation of array a has failed");
 exit(-1);
}

and when you want to increase its size:

tmp_a = realloc(a, 10000*sizeof(char));
if ( tmp_a == NULL ) // realloc has failed
{
 // error handling
 printf("The re-allocation of array a has failed");
 free(a);
 exit(-2);
}
else //realloc was successful
{
 a = tmp_a;
}

Eventually, remember to free the allocated memory, when the array is not needed anymore:

free(a);

Basically realloc(prt, size) returns a pointer to a new memory block that has the size specified by size and deallocates the block pointed to by ptr. If it fails, the original memory block is not deallocated. Please read here and here for further info.

Share:
10,021
Sowmya
Author by

Sowmya

Updated on June 04, 2022

Comments

  • Sowmya
    Sowmya almost 2 years

    I have written some code in C by taking the maximum size of char array as 100. It worked well. But when I increase the maximum size of char array to 10000 it gives me segmentation fault(as it has exceeded its limit). Can someone tell me how can I increase the maximum size and store a string of length 10000.

    i.e How can I take the "char a[100]" as "char a[10000]" and execute the same code????

    • Marcus Müller
      Marcus Müller almost 9 years
      There is no maximum size, there's only the reserved size. You seem to be making a mistake. Please post a complete, minimal example, and please make sure to format all source code as source code ({} button over input field).
    • Amol Saindane
      Amol Saindane almost 9 years
      Post the code which is used to operate on array a so that it will be more clear to resolve the issue
    • Gene
      Gene almost 9 years
      It's unusual for a modern machine to have a problem with an array of 10k. And seg fault is usually not the right error for an allocation limit problem. You probably have a bug that happens to be exposed by making the array bigger.