Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers to VLA's

As you may know, VLA's haves pros and cons and they are optional in C11.

I suppose that the main reason to make VLA's optional is: "the stack can blow up":

int arr[n]; /* where n = 1024 * 1024 * 1024 */

but what about pointer to VLA's?

int m, n;

scanf("%d %d", &m, &n);

int (*ptr)[n] = malloc(sizeof(int [m][n]));

In this case, there is no risk to blow up the stack, and IMO they are extremely useful.

My question is:

Could the committee have preserved pointers to VLA's, making the VLA's to non-pointer types optional?

Or one thing implies the other?

(Excuse my poor english)

like image 427
David Ranieri Avatar asked Oct 17 '22 10:10

David Ranieri


1 Answers

Preserving pointers to variably modifiable types would require an implementation to support about 90% of the VLA specification. The reason is the effective type rule:

6.5 Expressions

¶6 The effective type of an object for an access to its stored value is the declared type of the object, if any. If a value is stored into an object having no declared type through an lvalue having a type that is not a character type, then the type of the lvalue becomes the effective type of the object for that access and for subsequent accesses that do not modify the stored value. If a value is copied into an object having no declared type using memcpy or memmove, or is copied as an array of character type, then the effective type of the modified object for that access and for subsequent accesses that do not modify the value is the effective type of the object from which the value is copied, if it has one. For all other accesses to an object having no declared type, the effective type of the object is simply the type of the lvalue used for the access.

After an access via ptr to the malloced memory, the effective type of the object is a VLA type. So an implementation will need to support those semantics correctly. The only thing that can be left "optional" is the ability to declare VLA's with automatic storage duration...

int boo[n];

... which is kinda silly. If an implementation supports most of VLA semantics for dynamically allocated objects, it may as well allow declaring them as objects with automatic storage duration. The committee wanted it to be truly optional, so that means pointers to VLA types had to go too.

like image 200
StoryTeller - Unslander Monica Avatar answered Nov 02 '22 23:11

StoryTeller - Unslander Monica