-1

During initiation of char** map I print the values stored. When I then pass that pointer to a function, and print the values, the output is behaving weirdly.

If I don't print during the creation another, also not expected, behaviour occurs. What is going on?

void main(){
  char ** map = (char **) malloc(24);

  int i;
  for(i = 0; i < 24; i++){
    map[i] = (char *) malloc (sizeof(char));
    *map[i] = i;
    printf("%d\n", *map[i]);
  }

    display_map(map);

}

void display_map(char **m){
  int i;
  char bit;
  printf("\n");

  for(i = 0; i < 24 ; i++ ){
     bit = *m[i];
     printf("%d\n", bit);
  }
}

output:
0
1
2
3
.
.
23

48 //expected 0
1
2
3
.
.
23


If I however remove the print statement when I create char** map I get this output from display_map

output:
32   //expected 0
-96  //expected 1
32   //expected 2
-96  //expected 3
32   //expected 4
5
6
7
8
.
.
23

This is such a mystery to me.

toregh
  • 59
  • 1
  • 6
  • 2
    Out of bounds access, undefined behavior (unless the code is running on a *very* unusual machine). – EOF Apr 13 '19 at 13:24
  • @EOF are you able to see why this happens in my example? I can't wrap my head around it – toregh Apr 13 '19 at 13:28
  • 1
    Find out what `sizeof(char *)` evaluates to on your c implementation. – EOF Apr 13 '19 at 13:32
  • 1
    Specifically: `char ** map = (char **) malloc(24);` is enough room for 24 `char`s, not 24 `char*`s. – Ry- Apr 13 '19 at 13:35
  • sizeof char ** - 8 sizeof char * - 8 sizeof char - 1 – toregh Apr 13 '19 at 13:36
  • thank you! That worked! I multiplied by 8 and now it works :D @EOF – toregh Apr 13 '19 at 13:38
  • 1
    The size of a pointer doesn’t have to be 8, by the way, so you should use `malloc(24 * sizeof(char*))`. See also https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Ry- Apr 13 '19 at 13:41

1 Answers1

1

Change this

char ** map = (char **) malloc(24); /* memry allocated 24 char's, but you intended for 24 char pointer */

to

char **map = malloc(24 * sizeof(*map)); /* can use sizeof(char*) but it works for only char type while sizeof(*map) work for all data type */

And this

map[i] = (char *) malloc (sizeof(char));

to

map[i] = malloc(sizeof(**map));
asynts
  • 2,213
  • 2
  • 21
  • 35
Achal
  • 11,821
  • 2
  • 15
  • 37