小编ror*_*oro的帖子

strcpy周围的分段错误?

我知道你会用指关节敲打我但是.

为什么会出现分段错误

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)

但我只是想知道为什么这个分段错误.

谢谢 !

c segmentation-fault strcpy

5
推荐指数
2
解决办法
1万
查看次数

想要在strtok之后释放我的指针令牌

我已经提取了我的代码的"含义"部分(并且还替换了一些行来简化它).

我有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)

c free char strtok

4
推荐指数
1
解决办法
3227
查看次数

标签 统计

c ×2

char ×1

free ×1

segmentation-fault ×1

strcpy ×1

strtok ×1