Hello again!
It seems that I have received a problem when I added functionality using the above. I now created a function for adding a new "processes" to the array, but I'm getting segmentation fault, but I don't understand why. Can anyone see a problem? Here is the testprogram I'm using:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
struct process {
char* name;
int pid;
} *processes,*temp;
int number;
int addProcesses(int pid, char* newname)
{
int x;
if (number==0)
{
number++;
temp=malloc(number*sizeof(*processes));
temp[0].name=newname;
temp[0].pid=pid;
return(temp);
}
number++;
printf("Adding number %d\n",number);
temp=malloc(number*sizeof(*processes));
for (x=0;x<(number-1);x++)
{
temp[x]=processes[x];
}
temp[x].name=newname;
temp[x].pid=pid;
free(processes);
processes=temp;
free(temp);
return(0);
}
main()
{
int x=0;
number=0;
processes=addProcesses(35,"Testing");
processes=addProcesses(25," structs");
processes=addProcesses(15," again!");
for (x=0;x<number;x++)
printf("Pid: %d, Name: %s\n",processes[x].pid,processes[x].name);
exit(0);
}
By using printf-statements around the function (removed most of them before publishing here), I discovered that the segmentation fault occurs when I add the third string for some reason. As before I will use variables/pointers in stead of fixed strings in the end program, but I assume the functionality will be the same. I've tried without freeing also, but it didn't seem to make a difference.
Also, I put temp as another global variable as I couldn't figure out how to create a temp-array inside of the function and the returning it, but it wouldn't compile. Is that not possible (not as important as the main problem)?