[3/4] vhost: use alloca instead of vla sizeof

Message ID 1712250913-1977-4-git-send-email-roretzla@linux.microsoft.com (mailing list archive)
State Superseded
Headers
Series RFC samples converting VLA to alloca |

Checks

Context Check Description
ci/checkpatch success coding style OK

Commit Message

Tyler Retzlaff April 4, 2024, 5:15 p.m. UTC
  RFC sample illustrating conversion of VLA to alloca() where
sizeof(array) was in use.

Signed-off-by: Tyler Retzlaff <roretzla@linux.microsoft.com>
---
 lib/vhost/socket.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
  

Comments

Morten Brørup April 6, 2024, 10:30 p.m. UTC | #1
> From: Tyler Retzlaff [mailto:roretzla@linux.microsoft.com]
> Sent: Thursday, 4 April 2024 19.15
> 
> RFC sample illustrating conversion of VLA to alloca() where
> sizeof(array) was in use.
> 
> Signed-off-by: Tyler Retzlaff <roretzla@linux.microsoft.com>
> ---
>  lib/vhost/socket.c | 5 +++--
>  1 file changed, 3 insertions(+), 2 deletions(-)
> 
> diff --git a/lib/vhost/socket.c b/lib/vhost/socket.c
> index 96b3ab5..cedcfb2 100644
> --- a/lib/vhost/socket.c
> +++ b/lib/vhost/socket.c
> @@ -110,7 +110,8 @@ struct vhost_user {
>  {
>  	struct iovec iov;
>  	struct msghdr msgh;
> -	char control[CMSG_SPACE(max_fds * sizeof(int))];
> +	const size_t control_sz = sizeof(char) * CMSG_SPACE(max_fds *
> sizeof(int));

I get the point, but think multiplying with sizeof(char) is overkill.
It's a matter of personal taste; maybe it's just me.

If it was an array of a different type, e.g. int, multiplying with sizeof(int) would be required, like in the latencystats example.

Anyway, I agree with the approach here.

> +	char *control = alloca(control_sz);
>  	struct cmsghdr *cmsg;
>  	int got_fds = 0;
>  	int ret;
> @@ -124,7 +125,7 @@ struct vhost_user {
>  	msgh.msg_iov = &iov;
>  	msgh.msg_iovlen = 1;
>  	msgh.msg_control = control;
> -	msgh.msg_controllen = sizeof(control);
> +	msgh.msg_controllen = control_sz;
> 
>  	ret = recvmsg(sockfd, &msgh, 0);
>  	if (ret <= 0) {
> --
> 1.8.3.1
  

Patch

diff --git a/lib/vhost/socket.c b/lib/vhost/socket.c
index 96b3ab5..cedcfb2 100644
--- a/lib/vhost/socket.c
+++ b/lib/vhost/socket.c
@@ -110,7 +110,8 @@  struct vhost_user {
 {
 	struct iovec iov;
 	struct msghdr msgh;
-	char control[CMSG_SPACE(max_fds * sizeof(int))];
+	const size_t control_sz = sizeof(char) * CMSG_SPACE(max_fds * sizeof(int));
+	char *control = alloca(control_sz);
 	struct cmsghdr *cmsg;
 	int got_fds = 0;
 	int ret;
@@ -124,7 +125,7 @@  struct vhost_user {
 	msgh.msg_iov = &iov;
 	msgh.msg_iovlen = 1;
 	msgh.msg_control = control;
-	msgh.msg_controllen = sizeof(control);
+	msgh.msg_controllen = control_sz;
 
 	ret = recvmsg(sockfd, &msgh, 0);
 	if (ret <= 0) {