简体   繁体   中英

segmentation fault with array of string from file

I think I get understand how string works, but some how get a segmentation error when try to run this. I'm trying to create array of string that i read from file f. Also any comments for optimisation and or a better way to code (especially using pointer)is appreciated.

char a[700000][120];
char str[120];
int i=0,l,p;
while (fgets(str,120,f)) {
    strcpy(a[i],str);
    i++;
    }
int n=i;
for (i=0;i<=3;i++) {
    printf("%s\n",a[i]);
}

See if this helps

char **a;
int i;

a = malloc(700000 * sizeof(char*));
for (i = 0; i < 700000; i++) {
    a[i] = malloc(120*sizeof(char));
}

// read file here instead
strcpy(a[0],"hello");
strcpy(a[1],"goodbye");
strcpy(a[2],"yes");

for (i=0;i<=3;i++) {
    printf("%s\n",a[i]);
}

Per Michi, remember to free the memory afterwards.

for (i = 0; i < 700000; i++) {
    free(a[i]);
}
free(a);

Appendix Turns out you can check the stack size AND change it. Consider this

struct rlimit rl;
int result;

result = getrlimit(RLIMIT_STACK, &rl);

printf("stack limit %d\n", rl.rlim_cur);
printf("stack limit %d\n", rl.rlim_max);
return 0;

It gives me

stack limit 8388608
stack limit -1

(there is the 8MB).

There is a limit of array allocation, the size u are trying causes stack overflow of the function, because your array can't fit into the memory allocated to the function stack .

There is a limit of 8MB on the maximum size of objects, due to internal compiler implementation limits. You should use malloc() to create large arrays instead.

I think there is no need of creating str variable, you could have used the a itself. Moreover as mentioned in the comments too, try using dynamic memory, as most programmers don't use stack for huge allocations. May be heap may have greater size than stack.

In Linux Environment, ulimit -s can return the stack size.

root@ubuntu:# ulimit -s
8192

It means the max stack space that the system support is 8192 KB , that is 8MB . test program as follows, try to modify array size from 8*1024 to 7*1024.

#include<stdio.h>

void test()
{
}

int main()
{
    char a[7*1024][1024];
    test();
    return 0;
}

You can try this.

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

void main(void) {

    FILE *fp = NULL;
    fp = fopen("read.txt", "rb");
    if(fp == NULL)
        printf("failure\n");
    else
        printf("success\n");

    char buffer[4096];
    while (fgets(buffer, sizeof(buffer), fp) != 0)
        fputs(buffer, stderr);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM