-3

Old Test

I'm going over a test I took and am trying to figure out what the answer was to these questions. I was wondering if anyone could help me? As you can probably see I did not really understand how to answer them at the time but I would like to learn. I believed the answer has something to do with Malloc, but was unsure exactly how.

Thank you!

Edit : Is this how you do it?

    #include <stdio.h>
#include <stdlib.h>
float* func();
int main(void)
{
    float *x;
    x = func();
    printf("%f\n", *x);
    return 0;
}

float* func(void){
    float * z;
    z = malloc(sizeof(float));
    * z = 11.2;
    return z;
}
John Doe
  • 15
  • 1
  • 4

2 Answers2

0

As float z is defined locally in fucntion, it's allocated on stack. As a result it memory allocation is destroyed when function exits. As a result you will have a runtime error cause you are accesing a memory that do not belongs to you.

Juan Pablo
  • 1,213
  • 10
  • 15
0

malloc is related to allocating memory.

When we talk about array and pointer in c, we can seperate it into static array and dynamic array. For static array, we use array, for example,

char arr[10];

which means declare char type array named arr with length of 10. For Dynamic array, we use pointer, for example, char *arr. This means char type pointer of arr. Pointer is very flexible; therefore, you must command to use it properly.

Assume

char *arr = (char *) malloc (sizeof (char) * 10);

This means you have a pointer and will allocate the memory with the size of char type with length of 10 you can also re allocate memory with realloc with different length. At the end of using it you must

free(arr);

To add, this is benefit of C language and I believe it is harder to use than other languages but more flexibility. On the other hand, you must be very very careful using it. Unproperly used pointer could cause entire software failure.

Sean83
  • 493
  • 4
  • 14