Actually, the question is:

Why view code:

char *r = (char *)malloc(5 * sizeof(char)); 

runs without errors, that is, the memory is allocated normally, but in the code:

 char **r = (char **)malloc(5 * sizeof(char *)); 

I see in the value of the variable r the following -

 0xbaadf00d <error: Cannot access memory at address 0xbaadf00d> 

Why is that? For an array of characters, everything is normally allocated, but for an array of pointers there?

UPD : Similar allocation of memory for an array of pointers in another function works fine.

UPD2 : the value of r tracked through the debugger.

  • How do you see this ( r value)? printf("%p\n",r) ? - Harry
  • 3
    The problem is not memory allocation. The problem is with how this memory is then used. There is no relevant code in the question. - D-side
  • one
    Everything is normal , does not fall. - D-side
  • 2
    The second example allocates memory for 5 pointers to char* (yes, a pointer to pointers). But in those 20 bytes (5 * 4) the garbage is written. But the debugger does not yet know about them. and an attempt to read at these addresses is sad. Moreover baadfood hints. - KoVadim
  • one
    void main() { char **r = (char **)malloc(5 * sizeof(char *)); printf("%p\n",r); } void main() { char **r = (char **)malloc(5 * sizeof(char *)); printf("%p\n",r); } Compiles, displays something like 0041E050 ... What should I do to drop? - Harry

1 answer 1

In general, everything turned out to be easier nowhere:

  • initialization was really successful
  • after which the memory was allocated for the first element
  • this first element was a string from the data structure

And this very line from the structure came with the address 0x0. The function to get the data structure was not written by me, so I did not immediately suspect the exact location of the error. Forgive all those whom I did not believe

Thanks to all.