C language security encoding array notation consistency

  • 2020-04-02 02:20:49
  • OfStack

For C programs, Void func(char *a) in the same file;   and   Void func (char [] a); Completely equivalent

But outside of the function prototype, if an array is declared as a pointer in one file and an array in a different file, they are not equivalent

The sample code is as follows:


//main.c
#include<stdlib.h>
enum {ARRAYSIZE = 100};
char *a;
void insert_a(void);
int main(void) {
  a = (char*)malloc(ARRAYSIZE);
  if(a == NULL) {
    //Handling allocation error
  }
  insert_a();
  return 0;
}
//insert_a.c
char a[];
void insert_a(void) {
  a[0] = 'a';
}

The solution is as follows:


//insert_a.h
enum {ARRAYSIZE = 100};
extern char *a;
void insert_a(void);
//insert_a.c
#include "insert_a.h"
char *a;
void insert_a(void) {
  a[0] = 'a';
}
//main.c
#include<stdlib.h>
#include"insert_a.h"
int main(void){
  a = (char*)malloc(ARRAYSIZE);
  if(a == NULL) {
    //Handling allocation error
  }
  insert_a();
  return 0;
}

Related articles: