[英]Does strstr() return a pointer to malloced memory, requiring me to manually free it later?
I have a parser method that is parsing an API call.我有一个解析 API 调用的解析器方法。 I am using
strstr()
in my parsing function.我在解析函数中使用
strstr()
。 My parse_api
function is allowing me to return the pointer returned by strstr
.我的
parse_api
函数允许我返回strstr
返回的指针。 Am I correct in assuming that this means strstr
mallocs a memory space and I need to free it?假设这意味着
strstr
mallocs 内存空间并且我需要释放它,我是否正确?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
char *parse_api(char *str);
int main() {
char str[] = "dadsadsdsdsdamountdsafoodsd";
puts(parse_api(str));
return 0;
}
char *parse_api(char *str) {
char *needle;
char *updated_needle;
needle = strstr(str, "amount");
puts(needle);
updated_needle = needle + 9;
updated_needle[strlen(updated_needle) - 3] = '\0';
return updated_needle;
}
The strstr
function does not return alloc'ed memory.该
strstr
函数不返回alloc'ed内存。 It returns a pointer to the start of the substring inside of the haystack
parameter.它返回一个指向
haystack
参数内子字符串开头的指针。
So in this case strstr
will return str + 12
.所以在这种情况下
strstr
将返回str + 12
。
In the documentation, strstr
the following describes the returned value:在文档中,
strstr
下面描述了返回值:
Pointer to the first character of the found substring in
str
, or a null pointer if such substring is not found.指向
str
找到的子字符串的第一个字符的指针,如果未找到此类子字符串,则为空指针。 Ifsubstr
points to an empty string,str
is returned.如果
substr
指向一个空字符串,则返回str
。
When it says it returns a pointer to the first character of the substring, it means that quite literally.当它说它返回一个指向子字符串第一个字符的指针时,它的意思是字面意思。 It points to a location within
str
.它指向
str
一个位置。 In your case, it returns str + 12
.在您的情况下,它返回
str + 12
。 No memory is allocated.没有分配内存。
Note: This means that the value returned by strstr
stops being valid if str
is changed or freed!注意:这意味着如果
str
被更改或释放,则strstr
返回的值将不再有效!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.