Dynamic memory allocation on the stack

I recently tried this experiment, in which instead of switching to dynamic memory allocation for memory requirements of unknown size, I made a static allocation. When the array a[i]was declared by me, I saved the variable i(array size) and depended on the input that the user gives.

 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <conio.h>
 void function(int );
 int main(void)
 {
     int i;
     printf("Enter:");
     scanf("%d",&i);
     function(i);
     printf("i = %d\n",i);
     getch();
     return 0;
 }
 void function(int i)
 {
      char a[i];
      char b[4];
      strncpy(a,"hello",i);
      strcpy(b,"world");
      int j = 0;
      char *c = a;
      for( j = 0; j< 20; j++ )
           printf("%c",*c++);
 }

My questions:

  • Is such an operation legal?
  • If not, why does the compiler not give any warnings or errors?
  • Where will this memory be allocated: stack or heap?
  • Why does ANSI C / GCC allow this?
+3
source share
6 answers

Is such an operation legal?

.

VLA ANSI C99 pre-C99. GCC C99, , C99. ++ 0x.

, ?

gcc:

$ gcc -std=c89 src/vla.c  -Wall -ansi -pedantic
src/vla.c: In function β€˜function’:, not dynamic array.
src/vla.c:17: warning: ISO C90 forbids variable length array β€˜a’
src/vla.c:21: warning: ISO C90 forbids mixed declarations and code

"conio.h" MSDOS , , , Microsoft Visual ++, . MS , ++ 0x, , C. , .

: ?

, C .

ANSI C/GCC

, .

+11

C99.

StackOverflow.

+9

, . Visual Studio <= 2003 afaik .

, Ansi ++, gcc -ansi -pedantic.

+1

ANSI C (C89). , , /.

0
source

The code is valid, but one thing to keep in mind when using variable length arrays.

void function(int i)
{
     int a[i];
     .
     .
}

There are no errors. This code may fail if itoo large.

0
source

Dynamic memory allocation on the stack:

There is a library call _malloca that dynamically allocates memory on the program stack (very similar to malloc per heap)

Link: _ malloca

0
source

Source: https://habr.com/ru/post/1721566/


All Articles