I have a working C program where the length of an array of strings is known at compile time. It is:
char array_person_name[3][101];
char person_name[101] = "";
...
strncpy(person_name, "John Smith", strlen("John Smith")+1 );
for(i=0;i<3;i++)
{
sprintf(array_person_name[i], person_name );
}
When I check the first element using gdb it reads (e.g. “John Smith” + null character):
(gdb) p array_person_name[0]
$1 = "John Smith", '\000' <repeats 26 times>, "\003\000\t\000p\005\240 ?", '\000' <repeats 11 times>, "@\337\377\377\377\177\000\000\260\337\377\377\377\177\000\000\001\000\000\000\000\000\000\000\300\332\377\377\377\177\000\000\000\235\230Z5\000\000\000\260\337\377\377\377"
All the other elements in the array look similar. Now I need to modify this program so it works when the array size is not known at run time, where the result needs to be exactly the same as what is printed from gdb above (except, the characters after the null may be different). Here’s my code:
char **array_person_name;
char person_name[101] = "";
...
strncpy(person_name, "John Smith", strlen("John Smith")+1 );
array_person_name = malloc(3 * sizeof(char*)); /* allocate memory for row pointers */
for(i=0;i<3;i++)
{
array_person_name[i] = malloc(101 * sizeof(char)); /* allocate memory for columns */
sprintf(array_person_name[i], person_name );
}
When I then check the first element using gdb, it reads:
(gdb) p array_person_name[0]
$1 = 0x6cff30 "John Smith"
I’m not exactly sure what the difference between these two programs’ gdb outputs are, but whatever difference there is, is enough for a shared library, which accepts array_person_email as an input, to perform correctly for the first code block and incorrectly for the second code block. Is there a way to modify my second code block so that array_person_email looks the same as what results from the first code block?
The reason the output in GDB looks different is because in the first case, the
array_person_name[0]is an array whose size is known at compile-time, so GDB endeavours to display everything it knows about that array (i.e. all 101 elements). If you instead didp (char *)array_person_name[0], you would only get the “relevant” portion of the array.If your library function exhibits different behaviour, then either it’s broken, or you’re not passing it what it expects (i.e. it’s expecting something other than a
char **).