3

Getting some trouble with a function in C that basically creates and allocates a temporary array with help of the length of the name parameter + extension length.

int my_func(char *name)
{
    char *extension = ".db";
    size_t tmp_size = strlen(name) + strlen(extension);
    char tmp_name[tmp_size];
    
    return 0;
}

This does not however seem to work on MSVC but works fine on Clang or GCC. Any idea why I get these errors:

error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
error C2133: 'tmp_name': unknown size

When I use the debugger in Clang on macOS I see that it allocates and work fine. Why not for MSVC?

2
  • Just use a sufficiently large buffer, its size determined by MAX_PATH or pathconf. Allocate it using malloc. Write into that buffer using snprintf. Commented Nov 13, 2022 at 1:48
  • In my experience, the easiest way to rewrite code with variable-length arrays so that it works with MSVC is to use the function _alloca. That way, the memory will automatically be freed. Commented Nov 13, 2022 at 1:56

2 Answers 2

4

tmp_name is a variable length array, and such arrays are not supported in MSVC.

If you want this to work under MSVC you'll need to allocate space dynamically.

Also, your array is one element short as it doesn't have room for the terminating null byte for the combined string.

Sign up to request clarification or add additional context in comments.

Comments

1

Since tmp_size is a variable and not a fixed value you will have to allocate memory dynamically by using malloc you can also free the memory when you are done with it by using free.

Note: You will have to include stdlib header file to be able to access malloc and free functions

#include <stdlib.h>
#include <string.h>

int my_func(char *name)
{
    char *extension = ".db";
    size_t tmp_size = strlen(name) + strlen(extension);
    char *tmp_name;

    tmp_name = malloc(sizeof(*tmp_name) * tmp_size + 1 );
    
    
    return 0;
}

To Free The Memory After You Done Using The Array*

free(tmp_name);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.