c - 使用带有 malloced 指针的 strtok 正确地指向字符串
问题描述
我看到很多带有数组的 strtok 示例,但没有指向数组的指针。我随机拿了一个,并试图猜测它应该如何工作。它没有。为什么这会导致总线错误?
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main () {
char *str = malloc(16);
memset(str, '\0', 16);
str = "This - is - foo";
const char s[2] = "-";
char *token;
/* get the first token */
token = strtok(str, s);
/* walk through other tokens */
while( token != NULL ) {
printf( " %s\n", token );
token = strtok(NULL, s);
}
return(0);
}
解决方案
char *str = malloc(16); // you allocate memory
memset(str, '\0', 16); // you set it to zero
str = "This - is - foo";// you loose the reference to it assigning the pointer with the string literal reference
// now str references string literal
// as a bonus you got the memory leak as well
你能做什么?:
char *str = malloc(16);
strcpy(str, "This - is - foo");
或简单
char str[] = "This - is - foo";
或者
char *str = strdup("This - is - foo");
推荐阅读
- json - 用于将 curl 数据提取到 Google 表格的 Google 脚本功能
- sql-server - 根据 EF Core 中的二级索引获取数据
- node.js - 无法在 WebStorm 中运行 Jest
- django - 如何使用 Sendgrid 从部署在 Heroku 中的 Django 应用程序发送重置密码电子邮件?
- flutter - 未来
- > 无法分配给列表
- algorithm - 优化算法以在 4 秒内运行大量操作
- php - 在 magento 1.9 中上传图片
- javascript - React Navigation V5:导航到不同的屏幕
- python - 使用线程和信号处理程序时需要调用 exit() 两次退出
- c - C 插入换行问题(作业)