I have a parser method that is parsing an API call. I am using strstr()
in my parsing function. My parse_api
function is allowing me to return the pointer returned by strstr
. Am I correct in assuming that this means strstr
mallocs a memory space and I need to free it?
#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. It returns a pointer to the start of the substring inside of the haystack
parameter.
So in this case strstr
will return str + 12
.
In the documentation, strstr
the following describes the returned value:
Pointer to the first character of the found substring in
str
, or a null pointer if such substring is not found. Ifsubstr
points to an empty string,str
is returned.
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
. In your case, it returns str + 12
. No memory is allocated.
Note: This means that the value returned by strstr
stops being valid if str
is changed or freed!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.