Is it possible to have a (fixed) array which stores its elements in the read-only segment of the executable and not on the stack? I came up with this code but unfortunately it is very unflexible when it comes to adding, moving or deleting items. How do I verify that the strings are indeed stored in the read-only segment? I tried readelf -a file but it doesn't list the strings.
typedef struct {
int len;
int pos[100];
char data[500];
} FixedStringArray;
const FixedStringArray items = {
4,
{ 9, 14, 19, 24 },
"LongWord1Word2Word3Word4"
} ;
char* GetItem(FixedStringArray *array, int idx, int *len) {
if (idx >= array->len) {
/* Out of range */
*len = -1;
return NULL;
}
if (idx > 0) {
*len = array->pos[idx] - array->pos[idx - 1];
return & array->data[array->pos[idx - 1]];
}
*len = array->pos[idx];
return & array->data[0];
}
void PrintItem(FixedStringArray array, int idx) {
int len;
char *c;
int i = 0;
c = GetItem(&array, idx, &len);
if (len == -1) return;
while (i < len) {
printf("%c", *c);
*c++;
i++;
}
}
I am considering a script that automatically generates a struct for each array and uses the correct length for pos and data. Are there any concerns in terms of memory usage? Or would it be better to create one struct (like above) to fit all strings?