Segmentation error in C while allocation memory -
i total begginer @ c programming , trying write program reads value of "stat" file in /proc/. works first few entries, returns "segmentation error (core dumped)". far found out error has allocation of memory, cant seem find way fix it. code 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 = 1; while (pch != null) { if(i == statnumber) vals = pch; pch = strtok(null, " "); i++; } return vals; }
1) the
s=malloc(1024); should not while should oitside while loop , before while.
and free before leaving function:
free(s); 2) add
string[0] = '\0'; just after
char *string = malloc(buf.st_size); otherwise strcat not work properly
3) not need allocate memory str pointer because readfile function did
char* str = malloc(sizeof(readfile(path))); just replaced with
char* str; 4) , replace
char * pch = malloc(sizeof(str)); by
char * pch = str;
Comments
Post a Comment