Segmentation error in C while allocation memory

I am a total begginer at C programming and am trying to write a program that reads the value of "stat" file in /proc/. It works for the first few entries, but then it returns "Segmentation error (core dumped)". So far I found out that the error has to do with the allocation of memory, but I cant seem to find a way to fix it. My code so far is:

char* readFile(char* filename)
{
 FILE *fp;
    struct stat buf;
    fp=fopen(filename,"r");
    stat(filename,&buf);
    char *string = malloc(buf.st_size);
    char *s;
    while(!feof(fp))
    {
            s=malloc(1024);
            fgets(s,1024,fp);
            s[strlen(s)-1]='\0';
            strcat(string,s);
    }
    return string;

}

char* readStat(char* path, int statNumber)
{

  char* str = malloc(sizeof(readFile(path)));
  str = readFile(path);
  char * pch = malloc(sizeof(str));
  char * vals;
  pch = strtok (str," ");
  int i = 1;
  while (pch != NULL)
  {
  if(i == statNumber)
        vals = pch;
    pch = strtok(NULL, " ");
    i++;
  }
  return vals;

}

Answers


1) the

s=malloc(1024);

should not into the while it should be oitside the while loop and before the while.

And free it before leaving the function:

free(s);

2) add

string[0] = '\0';

just after

char *string = malloc(buf.st_size);

Otherwise the strcat will not work properly

3) You do not need to allocate memory for str pointer because the readFile function already did

char* str = malloc(sizeof(readFile(path)));

Just replaced with

char* str;

4) And also replace

char * pch = malloc(sizeof(str));

by

char * pch = str;

Need Your Help

How do I access the link to the content?

javascript jquery html

How do I access the content of link to by JavaScript and jquery

which is the best option for making mysql play well with gevent in a django app

python mysql django gevent gunicorn

I have a django app running on gunicorn with mysql as the database. I have added gevent in order to deal with multiple file uploads, but I am not sure what is my best driver option for making geven...