What is wrong with strcpy() in this code?
void process_filedata(char *filename)
{
void* content;
const char * buffer;
char * temp;
char * row;
char * col;
int lsize,buflen,tmp,num_scan; //num_scan - number of characters scanned
int m=0,p=0,d=0,j=0; //m - machine, p - phase, d- delimiter, j - job
FILE *file_pointer = fopen("machinetimesnew.csv","r");
if(file_pointer == NULL)
{
error_flag = print_error("Error opening file");
if(error_flag) exit(1);
}
fseek(file_pointer, 0 ,SEEK_END);
lsize = ftell(file_pointer);
buflen = lsize;
rewind(file_pointer);
// content = (char*) malloc(sizeof(char)*lsize);
fread(content,1,lsize,file_pointer);
buffer = (const char*) content;
strcpy(temp,buffer);
row = strtok(temp,"\n");
...............
...............
I am getting a segmentation fault..
There are actually three segmentation faults here:
The first one is
fread()which is attempting to write to memory that does not yet exist as far as your process is concerned.The second one is
strcpy(), (expounding on the first) you are attempting to copy to a pointer that points to nothing. No memory (other than the pointer reference itself) has been allocated fortemp, statically or dynamically.Fix this via changing
tempto look like this (allocating it statically):Or use
malloc()to dynamically allocate memory for it (as well as your other pointers, so they actually point to something), likewise forcontent. If you know the needed buffer size at compile time, use static allocation. If not, usemalloc(). ‘Knowing’ is the subject of another question.The third one is
strtok(), which is going to modifytempen situ (in place), which it obviously can not do, sincetempwas never allocated. In any event, don’t expecttempto be the same oncestrtok()is done with it. By the name of the variable, I assume you know that.Also, Initializing a pointer is not the same thing as allocating memory for it:
Finally, please get in the habit of using
strncpy()overstrcpy(), its much safer.