[英]segmentation fault double pointer
I'm having a segmentation fault on the following code and i really don't see what i missed, the aim of this code is to retrieve lines of a .csv and put them in a 2D array created with a double pointer. 我在以下代码上存在分段错误,我真的看不到我错过的内容,此代码的目的是检索.csv的行并将其放入使用双指针创建的2D数组中。
The seg fault is situated at the last assigment of plaintexts[i][j] for the 1st line of the csv file. 段错误位于csv文件第一行的明文[i] [j]的最后一次分配中。
Your help would be much appreciated (on this problem since yesterday...) 非常感谢您的帮助(从昨天开始就解决这个问题...)
int main(){
int n=48; //nbers of columns in csv file
int m=60; //nbers of lines in csv file
int cpt,i,j;
cpt=0;
i=0;
FILE *fp;
char *token;
const char s[2] = ",";
unsigned char **plaintexts;
plaintexts = malloc(sizeof(*plaintexts) * m);
char *str=malloc(sizeof(char)*15*n); //maximum 15 char per box
fp = fopen("aes_traces.csv","r");
while(fgets(str,15*n,fp)!=NULL){
plaintexts[i] = malloc(sizeof(*plaintexts[i]) * n);
token = strtok(str,s);
j=0;
while(token != NULL){
printf("%s\n", token);
token = strtok(NULL,s);
plaintexts[i][j]=(unsigned char) (*token);
j++;
}
i++;
free(str);
free(token);
}
fclose(fp);
}
while(token != NULL){
printf("%s\n", token);
token = strtok(NULL,s); // A
plaintexts[i][j]=(unsigned char) (*token); // B
j++;
}
If this loop runs at least once, it will end in a segfault. 如果此循环至少运行一次,它将以段错误结束。 Why?
为什么? The loop can't terminate until
token
is set to NULL in the line I marked A
and then dereferenced in the line I marked B
. 直到我在标记为
A
的行中将token
设置为NULL,然后在标记为B
的行中取消引用,循环才能终止。 Dereferencing a NULL will cause a segfault. 取消引用NULL将导致段错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.