I have the following algorithm to implement new in C
void *newinc(unsigned int s)
{
// allocate and align storage of size s
// handle failure via exception
// return pointer to storage
}
I have the following implementation:
void *newinc(unsigned int s)
{
int *p = (int *)malloc(s * sizeof(int));
return p;
}
I believe the first and the last step mentioned in the algorithm have been achieved by the program,how do I implement the second line in the algorithm:
// handle failure via exception
I believe C program does not have try/catch blocks to catch exceptions.
Are you sure you are wanting an implementation in C, not C++? The following is all under the assumption that you really want C.
To start with, C does not know the keyword
operator, and you cannot give a function a name with two words. Therefore you will need to give your function a different name, likeoperator_new. Given that your function obviously only works for ints (there’s no way in your interface to give information about the type, and your example implementation allocates space forsints), I’d suggestnew_intsinstead (since C doesn’t have constructors, the distinction betweennewandoperator newis moot). Alternatively you might want to pass on arguments telling about the size of the type you want to allocate. You can even pass on a pointer to a function you want to be called as “constructor” for your objects (using avoid*interface).Also C has no exceptions. You may somewhat emulate them with
setjmp/longjmp, however since C doesn’t know destructors it will not do cleanup for you. Code aware of your hand-made exception handling may however implement cleanup explicitly through a chain ofsetjmpbuffers. However, those setjmp buffers need to be passed on to your function, either using extra arguments, or using a global variable. All in all, the better option in C is to just returnNULL, asmallocdoes. However, if you insist on the exception part, this is how you might do it (untested):The function would then be called as follows: