2

I am not 100% sure whether I correctly allocated an array with 10 elements

char *str;


str = (int*)malloc(10 * sizeof(int)); 

The task was to allocate memory of string with 10 elements.

Have I done it correctly or do I have to add "+ 1" because of the '\0' at the end.

Thanks!

Tormund Giantsbane
  • 355
  • 1
  • 4
  • 12
Desibre93
  • 89
  • 11

1 Answers1

6

You have allocated many times more than you need. (sizeof(int) times to be precise). The correct would be

#define MAXLEN 10
...
str = malloc(sizeof *str*(MAXLEN+1));

Note that this will be sizeof(char) which is 1. So you can do this also

str = malloc(MAXLEN+1);

Check the return value of malloc as shown below: (malloc might not be able to service the request, it might return a null pointer. It is important to check for this to prevent later attempts to dereference the null pointer).

str = malloc(MAXLEN+1);
if(!str){
    perror("malloc");
    exit(EXIT_FAILURE);
}

Also void* to char* conversion is implicit - you don't need to cast the return value of malloc.

sizeof(*str) is a cleaner way to get the size of the type of the element for which we are allocating memory in str. The benefit is when you are later changing the code and making str point to an allocated memory which will contain int-s you don't need to look for sizeof(char) and then replace it with sizeof(int) it is done here by using sizeof(*str) automatically.

user2736738
  • 30,591
  • 5
  • 42
  • 56
  • But why do you do sizeof(*str) instead of sizeof(char) for example? – Desibre93 Jan 30 '18 at 18:29
  • @Desibre93.: Read the last part of the answer. – user2736738 Jan 30 '18 at 18:32
  • Thanks alot, but can I also write it simply like this str = malloc(11) ? – Desibre93 Jan 30 '18 at 18:34
  • @Desibre93.: Yes I have mentioned it.You can do that also..Instead of using 11..I used macro to hold that magic number – user2736738 Jan 30 '18 at 18:37
  • 2
    never write `malloc(11)`. When you read the code later - whats 11? (why not 12 or 42?) – pm100 Jan 30 '18 at 18:37
  • 2
    @Desibre93 basic programming technique: use constant defines for things like buffer sizes, string lengths, etc. Do not hard-code them in the code. For example, if you just used 11, then when you write a loop, say, to go through your buffer, you'd need a 10 or 11 there as well. Then later when you need to change the code to handle a different number, you have to find all the places that have that number. So use `#define MAXLEN 10` for the number of characters, and `MAXLEN+1` for the size of the needed buffer. Then if it has to change, you only have to change the value in `#define MAXLEN 10`. – lurker Jan 30 '18 at 19:29
  • @coderredoc if I write it like this char *string = (char\*)malloc((MAXLEN+1)*sizeof(char))); Is this correct as well? Will it work? – Desibre93 Jan 31 '18 at 23:32