-
malloc / new operator
I'm reading a tutorial from learncpp.com now, and I'm trying to create a variable(/pointer) with malloc/new, print it, and delete it.
Code:
#include <stdlib.h>
#include <stdio.h>
int main(int &argc, char **argv) {
int *pnValue = (int*) malloc(7);
*pnValue = 7;
printf("Pointer adress: %p\n", pnValue);
free(pnValue);
}
but, I got this:
Code:
mikalv@mikalv-laptop:~/Projects/CExamples$ gcc testalloc.cpp -o kake
/tmp/ccm9ZMkq.o:(.eh_frame+0x11): undefined reference to `__gxx_personality_v0'
collect2: ld returned 1 exit status
and I also tried this:
Code:
#include <stdlib.h>
#include <stdio.h>
int main(int &argc, char **argv) {
int *pnValue = new int;
*pnValue = 7;
printf("Pointer adress: %p\n", pnValue);
delete pnValue;
}
but this also fail, but with another message.
Code:
/tmp/cc0FszjM.o: In function `main':
dynamicallocation.cpp:(.text+0x19): undefined reference to `operator new(unsigned int)'
dynamicallocation.cpp:(.text+0x43): undefined reference to `operator delete(void*)'
/tmp/cc0FszjM.o:(.eh_frame+0x11): undefined reference to `__gxx_personality_v0'
collect2: ld returned 1 exit status
Can someone tell me what I'm doing wrong? and why I get these messages, so I can learn to next time..
-
Offhand, I see three mistakes:
- argc shouldn't be declared as being a reference, but just a straight int.... ie. int argc.
- malloc() needs an argument as to how many bytes to allocate. While it's a possibiliy an int may be seven bytes in size, that is unlikely. Allocate sizeof(int) or perhaps more preferably, sizeof(*pnValue).
- You should be using the C++ header file equivalents of the C header files: ie. cstdio instead of stdio.h and cstdlib instead of stdlib.h.
-
They both look like they should (or at least could) work, though the first one is weird because you allocate 7 bytes for an int, but an int is more likely 4 or 8 bytes. Also, note that main's first argument is usually passed by value, not by reference.
I suggest that you try:
Code:
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[]) {
int* pnValue = (int*)malloc(sizeof *pnValue);
*pnValue = 7;
printf("Pointer adress: %p\n", (void*)pnValue);
free(pnValue);
}
or for a more C++ish approach:
Code:
#include <iostream>
int main(int argc, char* argv[]) {
int* pnValue = new int;
*pnValue = 7;
std::cout << "Pointer adress: " << pnValue << '\n';
delete pnValue;
}
-
These errors mean that you're not linking against the C++ runtime. Compile with g++, not gcc.