I am a beginner to C. I have a function which returns an array and I am trying to print it but it is giving me segmentation fault, don't exactly know what I am doing wrong. Help would be much appreciated. Below is my code.
I want to know how I can make use of an array returned by a function (like printing the array and sorting them) and no, I cannot do them all in the main function, I have to make the function return the array and then print/sort the array.
#include <stdio.h>
int *getarray()
{
int arr[5] = {0,1,3,4,5};
return arr;
}
int main()
{
int *n;
n=getarray();
printf("\nElements of array are :");
for(int i=0;i<5;i )
{
printf("%d", n[i]);
}
return 0;
}
CodePudding user response:
The array you defined
int arr[5] = {0,1,3,4,5};
Has "automatic storage duration", which just means that the array will only exist during the execution of the function getarray()
. Once the function ends the array ceases to exist and the memory occupied by it is freed.
So when you try to access it you are causing undefined behaviour since your accessing some random part of memory you are not supposed to.
To fix this you can dynamically allocate memory for the array using malloc()
:
int *getarray() {
int *arr = malloc(sizeof(int) * 5);
if (arr == NULL) {
printf("malloc error");
return -1;
}
arr[0] = 0;
arr[1] = 1;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
return arr;
}
Or you could define the array as static
which means it will have "static storage duration" aka the array will remain for as long as the program does.
int *getarray() {
static int arr[5] = {0,1,3,4,5};
return arr;
}
CodePudding user response:
This is one of the basics in truly understanding and using C properly.
you are creating an array within a function, thus it's scope is limited to the lifetime of the function itself; thus, you are effectivey in main() referencing a pointer to memory which no longer exists.
CodePudding user response:
Your declaration int arr[5]
has function scope and is located on the stack. When the function returns the memory will get reused. Allocate the array where you will need it and pass the pointer around.
Add a declaration for memcpy
:
#include <stdio.h>
#include <string.h>
getarray
now gets a pointer where it can stores data. It uses memcpy
to copy the data.
void getarray(int * out_arr) {
int arr[5] = {0, 1, 3, 4, 5 };
memcpy(out_arr, arr, 5 * sizeof(int));
}
We now allocate memory on the heap and get a reference to this memory from malloc
. We have full control of this memory and we can pass this around without problems.
int main() {
int * n = malloc(5 * sizeof(int));
getarray(n);
printf("\nElements of array are :");
for (int i = 0; i < 5; i ) {
printf("%d", n[i]);
}
free(n);
return 0;
}
The memory needs to be released withfree()
when done unless you exit the program.
CodePudding user response:
I will answer this with a beginner-friendly approach. In C, every function has its own working area. When a function is called, this can also be main (), and working space is created, called an activation record. This activation record includes some local variables, return values, and some other information. It's like a temporary working environment. If the function did its job, for example, did some computation, it may return something and quits. After the function terminates, this returned thing should not depend on the memory place it is created. In your case, the array is a contiguous memory area, and it is created in the stack in your code. After the function quits, there is nothing in that address since it is cleaned. In other words, the activation record has been cleaned.
There are a couple of ways to achieve this goal:
Global array: This array would sit in the data segment of the memory and will stay there until the program quits. Every function will have access to this array (without needing it as a parameter).
Static keyword: Using static directly implies that you are putting this array into the data segment of your memory, and it will stay there until the program quits. However, static variables may be local (for example, if you use it in your getArray() function). There is a trick in the static keyword; if you use a function including a static keyword multiple times, the static variable is not initialized every time. You can skip that in other calls.
Heap: You need to understand pointers and dynamic memory allocation—research malloc(), NULL pointer, pointers, pointers-array relation, etc.
CodePudding user response:
C has different ways of allocating memory, stack, heap and static. In the code you're trying to return a pointer to a stack allocated variable which gets erased when the procedure returns. https://craftofcoding.wordpress.com/2015/12/07/memory-in-c-the-stack-the-heap-and-static/