Reputation: 558
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]);
}
Upvotes: 4
Views: 106
Reputation: 417
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);
}
Upvotes: 0
Reputation: 634
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;
}
Upvotes: 0
Reputation: 23394
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).
Upvotes: 2
Reputation: 34678
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.
Upvotes: 2
Reputation: 575
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.
Upvotes: 0