My C Foundation is not very good, also please know can explain, thank you
If I directly use code like the following, there will be a segfault error
char* ret = "Hello World"; Return_stringl (ret, strlen (ret), 0);
Whether RET is writing a string directly or initializing it first to char[100]
But as soon as the program is slightly improved, using dynamic memory allocation is fine:
char* Hello = "Hello world"; int len = strlen (hello); char* ret = (char*) emalloc (len); memcpy (ret, hello, Len); Return_stringl (ret, len, 0);
Added: Later found that the third parameter of Return_stringl to 1 will not have a cross-access error
Reply content:
My C Foundation is not very good, also please know can explain, thank you
If I directly use code like the following, there will be a segfault error
char* ret = "Hello World"; Return_stringl (ret, strlen (ret), 0);
Whether RET is writing a string directly or initializing it first to char[100]
But as soon as the program is slightly improved, using dynamic memory allocation is fine:
char* Hello = "Hello world"; int len = strlen (hello); char* ret = (char*) emalloc (len); memcpy (ret, hello, Len); Return_stringl (ret, len, 0);
Added: Later found that the third parameter of Return_stringl to 1 will not have a cross-access error
@ Phi-Phi answers The complete error, is purely misleading, did not expect to have been adopted. The string "Hello World" is a static string and is not inside the stack. char* Hello just points to it.
The essence of this problem is:
PHP itself is a type-safe scripting language, and for Return_stringl or return_string returned strings, PHP will be free at the appropriate time, so the programmer must ensure that the returned string is in the heap and can be free. That's why dynamic distribution is fine. and
char* ret = "Hello World";
Return_stringl (ret, strlen (ret), 0);
This returns a static string directly, causing PHP to make an error when the string is free.
Return_stringl and return_string The last argument, if it is 1, represents a copy of the string in the first argument that is copied back in the heap. This is the reason why the program is normal when the last parameter equals 1.
Obviously, this is a C-language understanding problem, and all the local variables within the function are allocated on the memory stack .
It is not controlled and is controlled by the compiler to control the area of the memory that is freed. It is usually released after the function is finished.
If you want to allocate a block of memory for a common function, you must use malloc
a similar function to explicitly allocate memory, of course, when you are done with it free
.
That's it. The third parameter remembers whether or not to copy