为什么分段错误? strtok 和 malloc
why segmentation fault? strtok and malloc
我有以下代码,在不使用 malloc
时可以完美运行,但是当我想添加动态内存分配时,它说分段错误,尽管它编译时没有警告或错误。为什么?
提前致谢
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXNUM 30
#define STR 200
#define MAXLEN 40
struct human { //Va
char name[MAXLEN];
char surname[MAXLEN];
int age;
float weight;
};
int main(int argc, char *argv[]) {
char *dlim= ",", *end = "\n", *stop = NULL;
char *tok, *string;
string = (char *)malloc(sizeof(char) * STR);
int i = 0, j = 0;
struct human man[MAXNUM];
FILE *fin = fopen("data.txt", "r");
if (string == NULL) {
printf("Memory not allocated");
}
if (fin == NULL) {
printf("Cannot open file\n");
exit(0);
}
while (fgets(string, sizeof(string), fin)) {
tok = strtok(string, dlim);
strcpy(man[i].name, tok);
tok = strtok(stop, dlim);
strcpy(man[i].surname,tok);
tok = strtok(stop, dlim);
man[i].age = atoi(tok);
tok = strtok(stop, dlim);
man[i].weight = atof(tok);
i++;
}
fclose(fin);
free(string);
j = i;
i = 0;
while (i < j) {
printf("%s %s %d %f \n", man[i].name, man[i].surname, man[i].age, man[i].weight);
i++;
}
return 0;
}
当您将 string
分配为 char
的数组时,sizeof(string)
不再为您提供数组的大小,而是为您提供指针的大小。因此,您必须更改循环以告知 fgets
数组的大小:
while (fgets(string, STR, fin)) {
...
或者更好,如果您将数组重新分配到大小 size
:
while (fgets(string, size, fin)) {
...
我有以下代码,在不使用 malloc
时可以完美运行,但是当我想添加动态内存分配时,它说分段错误,尽管它编译时没有警告或错误。为什么?
提前致谢
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXNUM 30
#define STR 200
#define MAXLEN 40
struct human { //Va
char name[MAXLEN];
char surname[MAXLEN];
int age;
float weight;
};
int main(int argc, char *argv[]) {
char *dlim= ",", *end = "\n", *stop = NULL;
char *tok, *string;
string = (char *)malloc(sizeof(char) * STR);
int i = 0, j = 0;
struct human man[MAXNUM];
FILE *fin = fopen("data.txt", "r");
if (string == NULL) {
printf("Memory not allocated");
}
if (fin == NULL) {
printf("Cannot open file\n");
exit(0);
}
while (fgets(string, sizeof(string), fin)) {
tok = strtok(string, dlim);
strcpy(man[i].name, tok);
tok = strtok(stop, dlim);
strcpy(man[i].surname,tok);
tok = strtok(stop, dlim);
man[i].age = atoi(tok);
tok = strtok(stop, dlim);
man[i].weight = atof(tok);
i++;
}
fclose(fin);
free(string);
j = i;
i = 0;
while (i < j) {
printf("%s %s %d %f \n", man[i].name, man[i].surname, man[i].age, man[i].weight);
i++;
}
return 0;
}
当您将 string
分配为 char
的数组时,sizeof(string)
不再为您提供数组的大小,而是为您提供指针的大小。因此,您必须更改循环以告知 fgets
数组的大小:
while (fgets(string, STR, fin)) {
...
或者更好,如果您将数组重新分配到大小 size
:
while (fgets(string, size, fin)) {
...