i trying to to open a text-file in read mode and passing that file pointer to a function which will extract the text from that file pointer ....
but every time i build and run the program i get the segmentation fault error at the start of the "loadtoFile" definition in GDb saying "cannot access memory at address 0x7fffffd237768"

#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <stdlib.h>
#include "cstring_cmp.h"

#define LENGTH 51

int loadToFile(FILE *f,int *file_pointer,int *length){

       
    *length++;
    double size=6000000;
    int i;
    char *substr[6000000-50+1];
    unsigned int no_of_strings;


    no_of_strings=size-*length+1;
    char *file=(char *)malloc(size);
    fread(file,size,1,f);

    for(i=0;i<no_of_strings;i++){

        substr[i]=(char*)malloc(LENGTH*sizeof(char));
        substr[i]=strndup(file+i,*length);

    }
    printString(*substr);

    qsort((void *)substr,no_of_strings,*length,cstring_cmp);

    printString(*substr);

    return 0;
}

i m calling the function like this

FILE *fp=fopen("1","r");
int length=50;
int file_pointer=1;
int resukt=loadToFile(fp,&file_pointer,&length);

Recommended Answers

All 2 Replies

Postfix operators bind more tightly than prefix operators. Therefore your *length++ gets parsed as *(length++) , which has undefined behavior because length + 1 isn't a pointer to the same object.

Also
1) Improper C syntax

int loadToFile(FILE *f,int *file_pointer,int *length){
    *length++;             // executable statement
    double size=6000000;   // definition statements
    int i;
    char *substr[6000000-50+1];
    unsigned int no_of_strings;

You must define your variables before executing any code

2) You may be trying to create too much data. 78M on each call with no indication of freeing up the malloced buffers.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.