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

Creating request stub with sinon in mocha

node.js mocha sinon

I'm using mocha to test some classes and I need to create a stub of request library.

Use AllJoyn Unity Extension

c# unity3d alljoyn

I need help integrating AllJoyn Unity Extension in my Unity project. I have managed to acquire SDK and create a unitypackage file and add it to my project. However compiling it just give me a DLL not

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.