How many chars can be in a char array?

后端 未结 6 738
广开言路
广开言路 2020-12-01 12:40
#define HUGE_NUMBER ???

char string[HUGE_NUMBER];
do_something_with_the_string(string);

I was wondering what would be the maximum number that I co

6条回答
  •  北海茫月
    2020-12-01 12:54

    It depends on where char string[HUGE_NUMBER]; is placed.

    • Is it inside a function? Then the array will be on the stack, and if and how fast your OS can grow stacks depends on the OS. So here is the general rule: dont place huge arrays on the stack.

    • Is it ouside a function then it is global (process-memory), if the OS cannot allocate that much memory when it tries to load your program, your program will crash and your program will have no chance to notice that (so the following is better:)

    • Large arrays should be malloc'ed. With malloc, the OS will return a null-pointer if the malloc failed, depending on the OS and its paging-scheme and memory-mapping-scheme this will either fail when 1) there is no continuous region of free memory large enough for the array or 2) the OS cannot map enough regions of free physical memory to memory that appears to your process as continous memory.

    So, with large arrays do this:

    char* largeArray = malloc(HUGE_NUMBER);
    if(!largeArray) { do error recovery and display msg to user }
    

提交回复
热议问题