dwurf
dwurf

Reputation: 12769

Segfault when trying to printf large char[]

The following code is segfaulting on me.

#include <stdio.h>

int main(int argc, char **argv)
{
    const int MEMSIZE = 1024*1024*10;
    char memblock[MEMSIZE];
    memblock[10] = '\0';

    printf("%s", memblock);

    return 0;
}

Is there some size limit on character arrays? I've forgotten all my C, am I doing something stupid here?

Upvotes: 0

Views: 285

Answers (2)

Davide Berra
Davide Berra

Reputation: 6568

Discover what's your max stack size with this small program, and check if your array is bigger

#include <stdio.h>
#include <sys/resource.h>

int main ()
{
    struct rlimit rl;
    int result = getrlimit(RLIMIT_STACK, &rl);
    printf("max stack size: %u\n", rl.rlim_cur);
}

result on my host

max stack size: 10485760

Local variables are stored into stack and, obviously, they can't be bigger than his max size

Upvotes: 5

simonc
simonc

Reputation: 42185

There's no limit on the size of char arrays as such but stack sizes will be relatively constrained compared to available heap memory. You're probably overflowing the stack here. You could try making memblock static

static char memblock[MEMSIZE];

or allocating it dynamically

char* memblock = malloc(MEMSIZE);
if (memblock == NULL) {
    printf("Error: failed to allocate %d byte buffer\n", MEMSIZE);
    return -1;
}
memblock[10] = '\0';
printf("%s", memblock);
free(memblock);

Upvotes: 3

Related Questions