Allocating and accessing array inside C function - c

I have written a function to allocate memory for an array and store the array length in a pointer so I can use both in my main function. Everything seems to work fine until I try to loop through the array printing the values.
When I use the array size pointer to terminate the print loop it shows strange behaviour. Could you please show me where I am going wrong?
Thanks in advance :)
#include <stdio.h>
#include <stdlib.h>
void func (int** arr, int** len){
int length = 5;
*len=&length;
*arr = malloc(sizeof(int)*(**len));
for (int i=0; i<(**len); ++i){
(*arr)[i]=i*10;
}
}
int main(){
int* len = NULL;
int* arr = NULL;
func(&arr, &len);
for (int i=0; i<5; ++i){
printf("%d\n", arr[i]);
} //works
/*
for (int i=0; i<*len; ++i){
printf("%d\n", arr[i]);
} //doesnt work
*/
free(arr);
return 0;
}

int length = 5;
*len=&length;
You here assign *len to point at a local variable (length). The local variable length will go out of scope when the function returns and dereferencing the pointer after that will have undefined behavior.
You'd get the correct behavior if you instead allocate the memory for the int in main and provide a pointer to that memory to func.
#include <stdio.h>
#include <stdlib.h>
void func(int** arr, int* len) { // int* instead
int length = 5;
*len = length;
*arr = malloc(length * sizeof **arr);
for (int i = 0; i < length; ++i) {
(*arr)[i] = i * 10;
}
}
int main() {
int len; // automatic storage
int* arr = NULL;
func(&arr, &len);
for (int i = 0; i < len; ++i) {
printf("%d\n", arr[i]);
} // now works
free(arr);
}

for (int i=0; i<*len; ++i){
printf("%d\n", arr[i]);
}
The above code doesn't work because the contents of len are indeterminate.
Using * with an indeterminate or NULL pointer has undefined behaviour.*
If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.¹
In the function func, lenght is a local variable, which is destroyed once the function returns.
The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address, and retains its last-stored value throughout its lifetime.²
For such an object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way.³
As the lenght is known at compile time and never changes, there's no need to pass a pointer to pointer to an int. Just pass an int for the allocation.
[1], [2], [3] — C11, 6.2.4 Storage Duration of Objects.

You should have worked correctly with the pointer. You passed a pointer to a pointer to a function and you're trying to write a value to the pointer.
int a = 0;
fun(&a);
{
*a = 42;
}
#include <stdio.h>
#include <stdlib.h>
void func (int** arr, int* len){
int length = 5;
*len=length;
*arr = malloc(sizeof(int)*(*len));
for (int i=0; i<(*len); ++i)
{
(*arr)[i]=i*10;
}
}
int main(){
int len = 0;
int* arr = NULL;
func(&arr, &len);
for (int i=0; i<5; ++i){
printf("%d\n", arr[i]);
} //works
for (int i=0; i<len; ++i){
printf("%d\n", arr[i]);
} //doesnt work
free(arr);
return 0;
}

Related

dynamic arrays int printing problem - maybe not a valid memory cell

#include <stdio.h>
#include <stdlib.h>
int find_lenght(int *arrr){
int i = 0;
while(arrr[i] != '\0'){
i++;
}
return i;
}
void init_array(int *arrr){
arrr=(int*)malloc(1*sizeof(int));
printf("New element:");
int lenght = find_lenght(arrr);
scanf("%d", &arrr[lenght]);
printf("Lenght = %d\n",lenght);
printf("Array elements are:\n");
for(int i = 0; i <= lenght; i++) {
printf("%d,", arrr[i]);
}
}
void print_array(int *arrr){
printf("Array elements are:\n");
int lenght = find_lenght(arrr);
for(int i = 0; i == lenght; i++) {
printf("%d,", arrr[i]);
}
}
int main() {
int *arr = NULL;
init_array(arr);
print_array(arr);
}
I don't know what am i missing here.
My point is to fill in and then print dynamic array
Also my taught is it's not filling the way it should, so it hasn't anything to print.
Your arr pointer in main is never assigned because your init_array assign the address of the allocated memory (the return value of malloc) to the input parameter arrr, which is, a local variable.
You have mainly two solutions to properly achieve what you want to do. The first one (the better one in my point of view), by making your init_array returning the allocated memory address to be assigned:
int* init_array()
{
int* retval = (int*)malloc(1*sizeof(int));
// ...
return retval;
}
int main()
{
int *arr = init_array(); //< assign arr with returned value
}
Another way is to make your init_array function taking a pointer to a pointer, so the function can assign this pointer:
void init_array(int** arrr)
{
(*arrr) = (int*)malloc(1*sizeof(int));
// ...
}
int main()
{
int* arr = NULL;
init_array(&arr); //< pass reference to arr
}
You need to pass the pointer to pointer to int to change passed pointer. Your for loop is invalid in print function. You need also to set the sentinel value yourself.
size_t find_length(const int *arrr)
{
size_t i = 0;
if(arrr)
while(arrr[i]) i++;
return i;
}
void add_element(int **arrr, int element)
{
size_t length = find_length(*arrr);
int *tmp = realloc(*arrr, (length + 2) * sizeof(**arrr));
if(tmp)
{
*arrr = tmp;
(*arrr)[length] = element;
(*arrr)[length + 1] = 0;
}
}
void print_array(const int *arrr)
{
printf("Array elements are:\n");
size_t lenght = find_length(arrr);
for(size_t i = 0; i < lenght; i++)
{
printf("arrr[%zu] = %d\n", i, arrr[i]);
}
}
int main(void) {
int *arr = NULL;
add_element(&arr, 5);
add_element(&arr, 15);
add_element(&arr, 25);
add_element(&arr, 35);
print_array(arr);
}
https://godbolt.org/z/drKej3KT5
the array on your main function is still NULL. the better way to do is just call the print_array() function after you initialize it. you just simply put print_array(arrr) inside init_array() and after the for loop statement.
The line
int lenght = find_lenght(arrr);
may invoke undefined behavior, because find_length requires its argument to be a pointer to the first element of a null-terminated int array. However, the content of the memory pointed to by arrr is indeterminate, because it has not been initialized. Therefore, it is not guaranteed to be null-terminated.

Returning a pointer to an array

I have written a function that creates a data table, initializes it's elements to 0 and returns a pointer to the data table. However it doesn't work. Could someone explain it to me so I understand where my problem is.
This is my code:
#include <stdio.h>
// Here I create the data table and initialize it's elements
int* tabinit(int size) {
int tab[size];
for (int i = 0; i < size; i++)
tab[i] = 0;
return tab;
}
int main() {
int* t = tabinit(10);
for (int i = 0; i < 10; i++)
printf("%d ", t[i]);
printf("\n");
return 0;
}
When a function terminates, then all its automatic variables go out of scope.
tab is an automatic variable in this case, and will go out of scope when the function terminates. Now you are returning a pointer to a local array, so when the array goes out of scope, you will find yourself with a dangling pointer.
Didn't your compiler warned you about this? I got, in GCC, this warning:
warning: function returns address of local variable [-Wreturn-local-addr]
return tab;
^~~
First make sure that you really want for practicing to create the array in the function. If not, then you don't need to, you could just create in main, and then pass it to the function.
But, if you want to practice, then you need to dynamically allocate the array, if you really want it to stay alive after the function terminates. In that case, the array will free its memory, only when you tell it to (so never forget to free).
Example:
#include <stdio.h>
#include <stdlib.h>
int* tabinit(int size) {
int *tab = malloc(size * sizeof(int));
for (int i = 0; i < size; i++)
tab[i] = 0;
return tab;
}
int main() {
int* t = tabinit(10);
for (int i = 0; i < 10; i++)
printf("%d ", t[i]);
printf("\n");
// do NOT forget to free
free(t);
return 0;
}
Output:
0 0 0 0 0 0 0 0 0 0
PS: When you get more familiar with malloc(), I suggest you read this: Should I check if malloc() was successful?
You should never return a pointer to a local object. After the function finishes, the local object gets deallocated and you're left with a dangling pointer (pointer that doesn't point to valid memory).
One way to do this would be to create your object in main and pass it into your function for init, like so:
void tabinit(int* tab, int size) {
for (int i = 0; i < size; i++)
tab[i] = 0;
}
int main() {
int t[10];
tabinit(t, 10);
for (int i = 0; i < 10; i++)
printf("%d ", t[i]);
printf("\n");
return 0;
}
Here:
// Here I create the data table and initialize it's elements
int* tabinit(int size) {
int tab[size]; // <------- here
for (int i = 0; i < size; i++)
tab[i] = 0;
return tab; // <------- also here
}
As gsamaras said, the content pointed by tab become out of scope after the function call. You can change this line:
int tab[size];
By:
int *tab;
tab = malloc(size * sizeof(int));
The content will be dynamically allocated, and then will remains after exiting from the function. However, you'll have to free it manually (free(t)) afterwards or it will be reserved until the end of the program (which could occur a memory leak).

Error with the malloc command in C

my Excercice is to initalise space from the heap in function1(); and to create an array there. In the main I have to print the array. What have I done wrong?
CODE
#include <stdio.h>
#include <stdlib.h>
int functionOne(int size);
int main()
{
int size = 0,i;
scanf("%d",&size);
int *arrsize = functionOne(size);
printf("rueckgabe %d",arrsize);
int arr [*arrsize];
arr[0] = 7;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
for(i=0; i<size; i++)
{
printf("[%d]",arr[i]);
}
}
int functionOne(int size)
{
int *arr;
arr = NULL;
arr = malloc(size * sizeof(int));
return arr;
}
The thing is on the line printf("rueckgabe %d",arrsize); you are printing the address returned by other function - that too using wrong format specifier.
Suppose you allocated memory for 4 int using the other function functionOne and the memory of the allocated chunk is being returned - now when you do *arrsize you are basically accessing the 0th positional int value. But as it is uninitialized - the value of it is indeterminate.
Earlier you were declaring VLA with uninitialized value. This is undefined behavior. Also there is no meaning printing the contents of the variable length array unless you initialize them (i.e.,printf("[%d]",arr[i]);).
Return value of the function functionOne is int but you are returning int*.
There are many other things you can follow in the code, like correcting the indentation - checking the return value of malloc and changing the signature of main from int main() to int main(void).
I have added some demo code showing whatever I have mentioned above:
Edit:
#include <stdio.h>
#include <stdlib.h>
int* functionOne(int size);
int main(void)
{
int size = 0;
if( scanf("%d",&size)!= 1){
fprintf(stderr,"Error in input\n");
exit(EXIT_FAILURE);
}
if( size <= 0){
fprintf(stderr,"Error in input [size]\n");
exit(EXIT_FAILURE);
}
int *arr = functionOne(size);
for(size_t i = 0; i < size; i++){
arr[i]=i;
}
for(size_t i = 0; i<size; i++){
printf("arr[%zu] = %d \n",i,arr[i]);
}
free(arr);
return 0;
}
int* functionOne(int size)
{
int *arr;
arr = malloc(sizeof(int)*size);
if( arr == NULL && size > 0){
perror("malloc");
exit(EXIT_FAILURE);
}
return arr;
}

How to return an array from a function with pointers

i'm trying to figure out how to return an array from a function in the main().
I'm using C language.
Here is my code.
#include <stdio.h>
int *initArray(int n){
int i;
int *array[n];
for(i = 0; i < n; i++){
array[i] = i*2;
}
return array;
}
main(){
int i, n = 5;
int *array[n];
array[n] = initArray(n);
printf("Here is the array: ");
for(i = 0; i < n; i++){
printf("%d ", array[i]);
}
printf("\n\n");
}
And this is the errors the console gives me:
2.c: In function ‘initArray’:
2.c:8:13: warning: assignment makes pointer from integer without a cast [enabled by default]
array[i] = i*2;
^
2.c:11:3: warning: return from incompatible pointer type [enabled by default]
return array;
^
2.c:11:3: warning: function returns address of local variable [-Wreturn-local-addr]
2.c: In function ‘main’:
2.c:23:4: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("%d ", array[i]);
^
It's impossible!
I hate being a noob :(
If you could help, with explanations, I would appreciate! :D
Edit: iharob's answer is better than mine. Check his answer first.
Edit #2: I'm going to try to explain why your code is wrong
Consider the 2nd line of main() in your question:
int *array[n];
Let's try to read it backwards.
[n]
says we have an array that contains n elements. We don't know what type those elements are and what the name of the array is, but we know we have an array of size n.
array[n]
says your array is called array.
* array[n]
says you have a pointer to an array. The array that is being pointed to is called 'array' and has a size of n.
int * array[n];
says you have a pointer to an integer array called 'array' of size n.
At this point, you're 3/4 way to making a 2d array, since 2d arrays consist of a list of pointers to arrays. You don't want that.
Instead, what you need is:
int * array;
At this point, we need to examine your function, initArray:
int *initArray(int n){
int i;
int *array[n];
for(i = 0; i < n; i++){
array[i] = i*2;
}
return array;
}
The second line of initArray has the same mistake as the second line of main. Make it
int * array;
Now, here comes the part that's harder to explain.
int * array;
doesn't allocate space for an array. At this point, it's a humble pointer. So, how do we allocate space for an array? We use malloc()
int * array = malloc(sizeof(int));
allocates space for only one integer value. At this point, it's more a variable than an array:
[0]
int * array = malloc(sizeof(int) * n);
allocates space for n integer variables, making it an array:
e.g. n = 5:
[0][0][0][0][0]
Note:The values in the real array are probably garbage values, because malloc doesn't zero out the memory, unlike calloc. The 0s are there for simplicity.
However, malloc doesnt always work, which is why you need to check it's return value:
(malloc will make array = NULL if it isn't successful)
if (array == NULL)
return NULL;
You then need to check the value of initArray.
#include <stdio.h>
#include <stdlib.h>
int *initArray(int n){
int i;
int *array = malloc(sizeof(int) * n);
if (array == NULL)
return NULL;
for(i = 0; i < n; i++){
array[i] = i*2;
}
return array;
}
int main(){
int i, n = 5;
int *array = initArray(n);
if (array == NULL)
return 1;
printf("Here is the array: ");
for(i = 0; i < n; i++){
printf("%d ", array[i]);
}
free(array);
printf("\n\n");
return 0;
}
You can't just return an array like that. You need to make a dynamically allocated array in order to do that. Also, why did you use a 2d array anyway?
int array[5];
is basically (not completely) the same as:
int * array = malloc(sizeof(int) * 5);
The latter is a bit more flexible in that you can resize the memory that was allocated with malloc and you can return pointers from functions, like what the code I posted does.
Beware, though, because dynamic memory allocation is something you don't wanna get into if you're not ready for tons of pain and debugging :)
Also, free() anything that has been malloc'd after you're done using it and you should always check the return value for malloc() before using a pointer that has been allocated with it.
Thanks to iharob for reminding me to include this in the answer
Do you want to initialize the array? You can try it like this.
#include <stdio.h>
void initArray(int *p,int n)
{
int i;
for(i = 0; i < n; i++)
{
*(p+i) = i*2;
}
}
void main(void)
{
int i, n = 5;
int array[n];
initArray(array,n);
printf("Here is the array: ");
for(i = 0; i < n; i++)
{
printf("%d ", array[i]);
}
printf("\n\n");
}
If you don't want to get in trouble learning malloc and dynamic memory allocation you can try this
#include <stdio.h>
void initArray(int n, int array[n]) {
int i;
for (i = 0 ; i < n ; i++) {
array[i] = i * 2;
}
}
int main() { /* main should return int */
int i, n = 5;
int array[n];
initArray(n, array);
printf("Here is the array: ");
for(i = 0 ; i < n ; i++) {
printf("%d ", array[i]);
}
printf("\n\n");
return 0;
}
as you see, you don't need to return the array, if you declare it in main(), and pass it to the function you can just modify the values directly in the function.
If you want to use pointers, then
#include <stdio.h>
int *initArray(int n) {
int i;
int *array;
array = malloc(n * sizeof(*array));
if (array == NULL) /* you should always check malloc success */
return NULL;
for (i = 0 ; i < n ; i++) {
array[i] = i * 2;
}
return array;
}
int main() { /* main should return int */
int i, n = 5;
int *array;
array = initArray(n);
if (array == NULL) /* if null is returned, you can't dereference the pointer */
return -1;
printf("Here is the array: ");
for(i = 0 ; i < n ; i++) {
printf("%d ", array[i]);
}
free(array); /* you sould free the malloced pointer or you will have a memory leak */
printf("\n\n");
return 0;
}

using pointers to display content of array

I am stuck about how to use pointers to display array. I can easily do this with array using for loop but I am interested in knowing how to use via pointers and I am stuck how to calculate starting and ending point of an array.
Below is the sample program
void printArray(int *ptr);
{
//for statement to print values using array
for( ptr!=NULL; ptr++) // i know this doesn't work
printf("%d", *ptr);
}
int main()
{
int array[6] = {2,4,6,8,10};
printArray(array);
return 0;
}
The checking for NULL trick only works for NULL terminated strings. For a numeric array you'll have to pass in the size too.
void printArray(int *ptr, size_t length);
{
//for statement to print values using array
size_t i = 0;
for( ; i < length; ++i )
printf("%d", ptr[i]);
}
void printString(const char *ptr);
{
//for statement to print values using array
for( ; *ptr!='\0'; ++ptr)
printf("%c", *ptr);
}
int main()
{
int array[6] = {2,4,6,8,10};
const char* str = "Hello World!";
printArray(array, 6);
printString(str);
return 0;
}
You have several options:
You could pass the size of your array into the function.
You could have a special "sentinel" value (e.g. -1) as the last element of your array; if you do this, you must ensure that this value cannot appear as part of the array proper.
When an array is passed as a parameter to a function, it is decayed into a pointer to the first element of the array, loosing the information about the length of the array. To handle the array in the receiving function (printArray) requires a way to know the length of the array. This can be done in two ways:
A special termination marker used for the last element. For strings this is NULL. In your example it could be -1, if that value will never occur in the real data.
Passing a length parameter to printArray.
This would give the following for statements:
//Marker value.
for(;*ptr != -1; ++ptr)
printf("%d", *ptr);
//Length parameter
for(int i = 0; i < length; ++i)
printf("%d", *(ptr+i));
The function needs to know the size of the array. There are two common approaches:
Pass the actual size to the function, e.g.
void printArray(int *ptr, size_t size)
{
int *const end = ptr + size;
while( ptr < end ) {
printf("%d", *ptr++);
}
}
int main()
{
int array[6] = {2,4,6,8,10};
printArray(array, sizeof(array) / sizeof(array[0]) );
return 0;
}
Explicitly provide a sentinel 0 (or other appropriate) element for the array:
void printArray(int *ptr);
{
//for statment to print values using array
for( *ptr != 0; ptr++) // i know this doesn't work
printf("%d", *ptr);
}
int main()
{
int array[6] = {2,4,6,8,10, NULL};
printArray(array);
return 0;
}
Here is the answer buddy (Non-tested)...
void printArray(int arr[]);
{
int *ptr;
for(ptr = &arr[0]; ptr <= &arr[5]; ptr++)
{
if(ptr != null)
printf("%d", *ptr);
ptr++; // incrementing pointer twice, as there are ‘int' values in array which
//are of size 2 bytes, so we need to increment it twice..
}
}
int main()
{
int array[6] = {2,4,6,8,10};
printArray(array);
return 0;
}

Resources