[英]strsep() with char pointer gives segmentation fault in c
int main() {
char* instruction = "x10, 14(x2)";
char* rd = strsep(&instruction, ",");
printf("%c", *rd);
return(0);
}
我试图运行这几行,我希望它打印“x”,但它给出了分段错误。 我做错了什么?
char *strsep(char **stringp, const char *delim); If *stringp is NULL, the strsep() function returns NULL and does nothing else. Otherwise, this function finds the first token in the string *stringp, that is delimited by one of the bytes in the string delim. This token is terminated by overwriting the delimiter with a null byte ('\\0'), and *stringp is updated to point past the token. In case no delimiter was found, the token is taken to be the entire string *stringp, and *stringp is made NULL.
您正试图通过将其传递给strsep
来修改仅就绪的字符串。
char* instruction = "x10, 14(x2)";
char* rd = strsep(&instruction, ",");
尝试
char* instruction = "x10, 14(x2)";
char *temp = strdup(instruction);
char *save = temp;
char* rd = strsep(&temp, ",");
free(save);
您需要保留指向temp
的指针的副本,以便以后可以将其释放。
示例:来自描述“ stringp 已更新为指向令牌之后。” 如果您使用free(temp)
,你会经过一个无效的地址, free()
因为temp
不再指向分配块的某处点在它的内部的开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.