How to resolve: error: initializer element is not constant

Sometimes during complex programing, there are chances we make some mistakes during hurry to write and complete the program so that we can test the features, in somewhat similar occasion, we faced an error during compilation as, “error: initializer element is not constant” , now as mentioned, if we have written multiple lines during coding and before compilation, it becomes difficult to remember we initialised which variable where..?

So, lets recreate similar error, with a very basic C program as below,

 $ vim helloerror.c 
#include <stdio.h>
#include <stdlib.h>

int *var = (int *)malloc(sizeof(int));

int main(int argc, char **argv) {
        *var = 10;
        printf("var is %d\n", *var);
        return 0;
}
 $ gcc -o helloerror helloerror.c 
 $ ./helloerror
helloerror.c:4:12: error: initializer element is not constant
 int *var = (int *)malloc(sizeof(int));
            ^

so, we got the mentioned error and during compilation, if the compiler is latest, it also shown the line of error.

Now, if we relooked at the code, we have a global integer pointer “var” and we are assining a memory to it by calling malloc, ideally this looks OK, but the catch is this is a “GLOBAL” variable, outside all the functions, so the program execution only initialises these variables once, so these are expected to be constants and not changing like we have done an assigned of it to memory returned by malloc.

SO, to avoid this error, always make sure all global variables are assigned with constants.

Now, lets rewrite this program to make sure error is gone,

#include <stdio.h>
#include <stdlib.h>

int *var = NULL;

int main(int argc, char **argv) {
        var = (int *)malloc(sizeof(int));
        *var = 10;
        printf("var is %d\n", *var);
        return 0;
}

Changes are done in “int *var = NULL;” and moving malloc statement inside main.

Android Android Commands Android Java Applications Application Libraries Bash / Shell Scripts Bluetooth driver Build Frameworks Commands and Packages Core Kernel C Programs Development Environment Setup Documents / Books Errors & Failures File Systems Framebuffer / Display Driver git Go Language Programs Hardware Platforms Home JAVA Programs Kernel & Device Drivers Kernel Booting and Porting Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL NDK / Middleware / HAL Network Driver OS Concepts PHP Procfs Filesystem Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded
Tags: ,

Leave a Reply