Context
I was experimenting with getting C strings in C++ without allocating memory on the heap and came across this in testing:
#include <stddef.h>
#include <stdlib.h>
char* get_empty_c_string(size_t length) {
char buffer[length];
char *string = buffer;
for (size_t i = 0; i ^ length; i++) *(string + i) = '\0';
return string;
}
int main(void) {
char *string = get_empty_c_string(20u); // Allocated on heap?
// or stack?
return 0;
}
Question
Is the C string returned allocated on heap or stack?
As far as I know:
Heap allocation occurs with the
calloc,malloc&reallocC standard functions ornew&new[]C++ keywords.Stack allocation in most other cases.
char buffer[length];-- This is not valid C++.stringis not usable inmain.-Walland this was not mentioned...-pedantic-errorsflag.