c++ - incompatible implicit declaration of built-in function 'malloc' -
my program is
#include <iostream> char * grabnumber ( char * begin ) { // interpret *begin start of double , add characters // string retstr char * begincpy = begin; int founddot = 0; while ((*begin >= '0' && *begin <= '9') || *begin == '.') { if (*begin == '.') { if (founddot == 0) founddot = 1; else break; } ++begin; } long n = begin - begincpy; // # of characters parsed char * retstr = malloc(sizeof(char) * (n + 1)); // string returned (long k = 0; k < n; ++k) retstr[k] = *begincpy++; retstr[n] = '\0'; return retstr; } int main() { char str [] = "abc3.14def"; std::cout << grabnumber(str+3); // should print "3.14" return 0; }
and errors i'm getting are
line 20: warning: incompatible implicit declaration of built-in function 'malloc' line 21: error: 'for' loop initial declaration used outside c99 mode
corresponding 2 lines
char * retstr = malloc(sizeof(char) * (n + 1)); // string returned (long k = 0; k < n; ++k) retstr[k] = *begincpy++;
see: http://codepad.org/c2tngfeo
also, there way can cut down on redundancy of algorithm, because it's checking .
twice in each iteration of while
loop, , yet can't think of cleaner way handle fact need stop loop if we've run second .
i'm guessing trying write c++ have included iostream
, used std::cout
. error message shows using c compiler. guess wrote gcc myprogram.c
. c++ compilation either need write g++
instead of gcc
, or rename file have .cc
extension. (preferably both).
to use malloc
need #include <cstdlib>
.
also may need using namespace std;
or using std::malloc;
after that; , need cast value returned malloc
because c++ not implicitly convert void *
other pointer types.
however malloc
used in c++ not initialize non-trivial objects properly. consider changing code to:
char * retstr = new char[n+1];
then won't need includes.
but still weak design relying on caller free memory. in fact main
function has memory leak not free memory.
in c++ better style have memory managed container class knows memory management; programmer can't make mistakes. (incase wondering, doesn't introduce inefficiency , may speed things up).
a better approach #include <string>
, make function return std::string
, , change last 5 lines of function to:
return { begincpy, begin };
or if using pre-c++11 compiler,
return std::string(begincpy, begin);
Comments
Post a Comment