Leo*_*313 2 c malloc free segmentation-fault
执行此简单程序时出现段错误(这只是重现错误的精简版本)。
// gcc main.c -Wall -Wextra -Wpedantic
// ./a.out
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h> // uint32_t
int main(){
char* rest = (char*)malloc(128 * sizeof(char));
char* token= (char*)malloc(128 * sizeof(char));
strcpy(rest,"Something_else");
token = strtok_r(rest, "_", &rest);
printf("%s\n", token);
free(token);
free(rest);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
该free变量的token不给任何错误。该free变量的rest给我总是分割故障我每次使用该功能时strok_r。到底是怎么回事?有什么建议吗?编译时无警告提示。
问题:
如何正确地重写此简单代码?
您只需要为句子存储空间,token而rest仅仅是指针。
使用while循环,您可以看到所有标记:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h> // uint32_t
int main(){
char* rest , *token;
char* setence= malloc(128 * sizeof(char));
strcpy(setence, "Some_thing_else");
token = strtok_r(setence, "_", &rest);
while (token)
{
printf("%s\n", token);
token = strtok_r(NULL, "_", &rest);
}
free(setence);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
会给:
Some
thing
else
Run Code Online (Sandbox Code Playgroud)