I have created a macro to make reserve memory for my strings in C. It looks like this:
#define newString(size) (char*)malloc(sizeof(char) + size)
So is there any reason I shouldn’t use this macro in my own personal projects? I know I shouldn’t do this in production code because it would require everyone to have that header file and everyone to know that newString was a macro.
(char*)malloc(sizeof(char) * (size+1))would be more appropriate (the +1 is to account for the NULL at the end of string, if applicable).If one is copying a string, strlen() doesn’t account for the NULL terminating the string hence an additional memory
charis required.