问题
I am currently working on a project for a course in C programming and have run into a problem. I am still quite new to the language C but have experience programming Java.
My program runs into a problem when I try to assign a value to a char * variable member of a struct. The code in question follows below:
void ReadFile(ComponentType * Data, int * numEl, int * numNodes)
{
size_t index;
FILE * dataFile;
char * data;
float * value;
numEl = malloc(sizeof(int *));
numNodes = malloc(sizeof(int*));
Data = malloc(6 * sizeof(ComponentType));
* numEl = 0;
* numNodes = 0;
index = 0;
if((dataFile = fopen("mydata.dat", "r")) == NULL)
puts("Error - file \"mydata.dat\" could not be opened!");
else
{
while(!feof(dataFile))
{
fscanf(dataFile, "%s", data);
Data[index].name = (char *)malloc(strlen(data)+1);
strcpy(Data[index].name, data);
fscanf(dataFile, "%s", data);
Data[index].node1 = (char *)malloc(strlen(data)+1);
strcpy(Data[index].node1, data);
fscanf(dataFile, "%s", data);
Data[index].node2 = (char *)malloc(strlen(data)+1);
strcpy(Data[index].node2, data);
fscanf(dataFile, "%f", value);
Data[index].value = * value;
int i = char2int(CircuitData[index].node1);
if(i > * numNodes)
* numNodes = i;
i = char2int(CircuitData[index].node2);
if(i > * numNodes)
* numNodes = i;
(* numEl)++;
(* numNodes)++;
index++;
}
fclose(dataFile);
}
free(Data);
free(numEl);
free(numNodes);
}
The structure is defined as follows:
typedef struct
{
char * name;
char * node1;
char * node2;
float value;
} ComponentType;
I have run a debug on the program and what basically happens is that the file is read correctly and the value stored in data is correct however printing out Data[index].name either causes a segmentation fault when formatted as a char * or, in the debug program, prints out 0x0. In short, the values read from the file are not being copied into the structure variable I want them in.
Any suggestions/help would be appreciated. Thank you.
EDIT: I am using Linux 64-bit to code
EDIT 2: I added the entire function in which the error occurs with the changes suggested below
回答1:
First: when you debug your program, check what sizeof(data) is.
You will be surprised to find it is 8 (the size of a pointer), and NOT 6 (the size you allocated)
This is because sizeof measures the size of the type, and data is a char*, (aka. a pointer).
Pointers are 8-bytes. (on a 64-bit system. Other systems are different)
This causes you to allocate 8 bytes for Data[index].name.
Next: You cannot copy data from one array to another using the = operator, as you tried to do with:
Data[index].name = data;
To do it properly:
fscanf(dataFile, "%s", data);
// Measure the length of data, and allocate enough space (including the null-termiantor)
Data[index].name = malloc(strlen(data) + 1);
// Copy from data into Data[index].name. For greater safety, look into strcpy_s
strcpy(Data[index].name, data);
来源:https://stackoverflow.com/questions/19255964/assigning-values-to-members-of-structures