0

Sample Code



struct ArrayList {
    char* string;
    int index;
    int capacity;
};



array initialize(int cap) {
  array list;
  
  list.index = 0;
  list.capacity = cap;
  list.string = malloc(sizeof(char));
  return list;
}

void addElement(arrayPtr list, char c) {
  list->string[list->index] = c;
  list->index += 1;
}

I initialized string for 1 char only but I was able added more than what the array should have been I added 11 char elements and it was possible and it printed in the terminal as well.

I tried adding more but it didnt error. As far as I know for char I can only access one letter, but it was able to input me a word.

  • 1
    The behavior of *undefined behavior* is, well, undefined. Anything is allowed to happen, including the program appearing to work correctly – UnholySheep Oct 27 '22 at 08:15
  • Your "capacity" isn't really the amount of allocated memory. And you should *always* check the bounds of arrays or allocated memory. Remember that C doesn't have any kind of bounds-checking itself, it's up to your as the programmer to make sure code doesn't go out of bounds. – Some programmer dude Oct 27 '22 at 08:16
  • Ahhh Ic thanks for the explanation, I was wondering why I was able to access those part. – Jethro Cenas Oct 27 '22 at 08:19
  • 1
    Please don't post code as pictures, post it all as text, as you have already done for a part of your program. You have also left out something (I suppose you have `typedef struct ArrayList array;` somewhere?) – Fabio says Reinstate Monica Oct 27 '22 at 08:20
  • Curious: What did you expect to happen? – hyde Oct 27 '22 at 10:22
  • I thought if it get out of the index on how I initialized the string, it will get error. But I was able to access the memory outside of the scope. when I initialized it to sizeof(char) only I was able to add 11 characters instead of 1. – Jethro Cenas Oct 27 '22 at 11:12

0 Answers0