简体   繁体   中英

function returning pointer vs function returning array in C

func1 is giving warning & junk value while func2 is giving the right output. 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.

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 .

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 ). 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 .

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).

The dynamic array ( ex. unsigned char *data=malloc(6); ) sticks around forever until you free() it. It's lives on the heap.

Function 1 returns a pointer to the local variable (allocated on stack). 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.

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.

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