[英]Better way to return the value from a function
#include<stdio.h>
char* my_strcpy(char* source, char* destination) {
char* p = destination;
while( *source != '\0' ) {
*p++ = *source++;
}
*p = '\0';
return destination;
}
int main() {
char stringa[40] = "Time and tide wait for none";
char stringb[40];
char *ptr;
char *ptr1;
ptr = stringa;
ptr1 = stringb;
puts(stringa);
puts(ptr);
my_strcpy(ptr, ptr1);
puts(ptr);
return 0;
}
Here the variable destination
, as the local copy of the function, is returning the pointer is safe. 作为函数的本地副本,这里的变量
destination
是返回指针的安全对象。 I believe it will be safe as long as the address is used immediately after returning or else what if some other process uses the address, it will be changed. 我相信只要返回后立即使用该地址就可以安全使用,否则如果其他进程使用该地址,该地址将被更改。 How to return safely without doing
return destination
? 如何在不
return destination
情况下安全return destination
?
Is it possible to do a malloc for p
and return it rather than assigning the location pointed by destination
? 是否可以为
p
做一个malloc并返回它,而不是分配destination
指向的位置?
destination
isn't controlled by my_strcpy
, so what happens to it outside of the function is irrelevant to my_strcpy
. destination
不受my_strcpy
控制,因此在函数之外发生的事情与my_strcpy
无关。 That is to say, it's perfectly safe and expected for the function to return destination
. 这就是说,函数返回
destination
绝对是安全的。 Whoever called my_strcpy
will be responsible to make sure the variable's memory is ok. my_strcpy
负责确保变量的内存正常。 Returning the destination
variable is simply a convenience for function chaining. 返回
destination
变量只是函数链接的一种便利。
You could malloc and return a new area of memory (though then you wouldn't need a destination
parameter). 您可以malloc并返回一个新的内存区域(尽管那样就不需要
destination
参数了)。 This is basically the functionality of strdup
, and it's the responsibility of the caller of strdup
to free the memory that was allocated. 这是基本的功能
strdup
,和它的调用者的责任strdup
释放已分配的内存。
Note, there's no risk of another process corrupting the memory. 请注意,没有其他进程破坏内存的风险。 Unless you're dealing with shared memory, processes each have access to only their memory.
除非您要处理共享内存,否则每个进程只能访问其内存。 Some function later on in this process could change what you did in
my_strcpy
, but that's not the problem of my_strcpy
. 此过程后面的某些功能可能会更改您在
my_strcpy
所做的my_strcpy
,但这不是my_strcpy
的问题。 As for it being safe if it's used immediately after the function, you're copying into space that was assigned to you. 如果在函数之后立即使用它是安全的,那么您将复制到分配给您的空间中。 The
p
value isn't the memory you're writing into; p
值不是您要写入的内存; it's just the pointer to the memory. 它只是指向内存的指针。 And the memory itself isn't on the stack.
而且内存本身不在堆栈中。 As jpw mentioned at some point - you don't need the
p
variable at all. 正如jpw提到的那样-根本不需要
p
变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.