Segmentation error with array of string from file

I think I understand how the string works, but some of them get a segmentation error when trying to run it. I am trying to create an array of a string that I read from file f. Any comments for optimization and / or the best coding method are also evaluated (especially using a pointer).

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]);
}
+4
source share
5 answers

See if it 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, don't forget to free your memory afterwards.

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

Application . 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 8 MB).

+2
source

, u , , stack.

8 - . malloc() .

+2

, str, a. , , , . , , .

+1

Linux ulimit -s .

root@ubuntu:# ulimit -s
8192

This means that the maximum stack space supported by the system is 8192 KB , 8 MB . follow the procedure below, try resizing the array from 8 * 1024 to 7 * 1024.

#include<stdio.h>

void test()
{
}

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

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);

}
0
source

All Articles