我知道你会用指关节敲打我但是.
为什么会出现分段错误
char* cmd;
strcpy(cmd, argv[0]);
Run Code Online (Sandbox Code Playgroud)
当这不
char *cmd;
cmd = "plop";
Run Code Online (Sandbox Code Playgroud)
我一段时间没有练习,也不记得为什么.
ps:实际上,我知道在strcpy之前会有更好的东西
char *cmd = (char*) malloc(strlen(argv[0]));
Run Code Online (Sandbox Code Playgroud)
但我只是想知道为什么这个分段错误.
谢谢 !
我已经提取了我的代码的"含义"部分(并且还替换了一些行来简化它).
我有2个动态指针,一个用于当前行(从文件中提取),另一个用于当前令牌.在这个问题之后,在处理完整的字符串之前,自由/删除strtok_r指针? 我写了这个:
int main(void) {
int n = 455;
char *tok2, *freetok2;
char *line, *freeline;
line = freeline = malloc(n*sizeof(*line));
tok2 = freetok2 = malloc(n*sizeof(*tok2));
/* content of the file) */
const char* file_reading = "coucou/gniagnia/puet/";
/* reading from the file */
strcpy(line, file_reading);
strtok(line, "/");
/* get the second token of the line */
tok2 = strtok(NULL, "/");
fprintf(stdout, "%s \n", tok2); // print gniagnia
fprintf(stdout, "%s \n", line); // print coucou
/* free error …
Run Code Online (Sandbox Code Playgroud)