Reputation: 409
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;
}
Upvotes: 0
Views: 147
Reputation: 409136
To start with, you don't allocate space for the terminator for the string
variable. You also need to terminate it before you can use it as a destination for strcat
.
To continue, when you do sizeof
on a pointer, you get the size of the pointer and not what it points to. You have this problem in readStat
.
You also have memory leaks, in that you call readFile
twice, but never free the memory allocated in it. Oh, and one of the memory allocations in readFile
is not needed at all.
And there's another memory leak in that you allocate memory for pch
, but you loose that pointer when you assign the result of the strtok
call. strtok
returns a pointer to the string in the strtok
call, so no need to allocate memory for it (which you didn't attempt to free anyway).
Upvotes: 1
Reputation: 43518
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;
Upvotes: 2
Reputation: 1
s=malloc(1024); should not be in loop, you should allocate the memory once and reset s with NULL before use next time in loop. Also you should make a habit to free the memory after its usage.
Upvotes: 0