简体   繁体   English

函数返回指针vs函数返回数组

[英]function returning pointer vs function returning array in C

func1 is giving warning & junk value while func2 is giving the right output. func1提供警告和垃圾值,而func2提供正确的输出。 What's the difference between the two? 两者有什么区别?

//func 1
unsigned char *CreateData()
{
unsigned char data[]="Thanks";
return data;
}

/* func 2
unsigned char *CreateData()
{
unsigned char *data=malloc(6);
strncpy(data,"Thanks",strlen("Thanks"));
return data;
}


int main()
{
unsigned char *a;
a=CreateData();
printf("%s",a);
return 0;
}

Thanks :) 谢谢 :)

Using the first implementation of CreateData , you return a pointer to a variable with automatic storage duration and then use it past its lifetime, which is undefined behavior. 使用CreateData的第一个实现,您将返回一个指向具有自动存储持续时间的变量的指针,然后在其生命周期结束后使用它,这是未定义的行为。

Less formally, what's actually happening is that data is allocated on the stack, and once you get around to using it as a , CreateData has ended and that stack space is now available for other functions to use, like main or printf , and those other functions are trampling over the space that was previously reserved for data . 非正式地讲,实际发生的是在堆栈上分配了data ,一旦您将其用作aCreateData已经结束,并且堆栈空间现在可供其他函数使用,例如mainprintf ,以及其他函数在以前为data保留的空间上践踏。

When you use malloc , though, the memory is said to be allocated on the heap, not on the stack, and memory on the heap is only released when you tell it to be released (using free ). 但是,当您使用malloc ,据说内存是在堆上分配的,而不是在堆栈上分配的,堆上的内存只有在告诉它要释放时才释放(使用free )。 Unlike with variables with automatic storage duration, the memory will not be released when CreateData has returned, so you can continue to use that memory in main . 与具有自动存储持续时间的变量不同,在CreateData返回后不会释放内存,因此您可以继续在main使用该内存。

The static array ( ex. unsigned char data[]="Thanks"; ) will be destroyed as soon as you leave the current stack frame (basically, when the function you're in returns). 静态数组( ex. unsigned char data[]="Thanks"; )将在您离开当前堆栈帧后立即销毁(基本上,当您使用的函数返回时)。

The dynamic array ( ex. unsigned char *data=malloc(6); ) sticks around forever until you free() it. 动态数组( ex. unsigned char *data=malloc(6); )永远存在,直到您free()free() It's lives on the heap. 它生活在堆上。

Function 1 returns a pointer to the local variable (allocated on stack). 函数1返回一个指向局部变量的指针(分配在堆栈上)。 This is an undefined behaviour. 这是未定义的行为。

In Function 2, the data block is allocated on the heap, hence its value persists out of the scope of the function. 在函数2中,数据块是在堆上分配的,因此其值会持续存在于函数范围之外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM