0

I feel confused about lambda in c++.Is it related to the compiler? The following code run correct in ubuntu g++ 4.6.3 and g++ 5.2. But when I run it in centos 4.8.5,the result is error.

// 
class ScopeGuard
{
 public:
    explicit ScopeGuard(std::function<void ()> onExitScope)
      :onExitScope_(onExitScope)
 {

 }

   ~ScopeGuard()
  {
     onExitScope_();
  }
private:
  std::function<void ()> onExitScope_;
};

And there is a function to uncompress the data.

//
...
int dstLen = 10 * 1024 * 1024;
char *dstBuf = new char[dstLen];
// When I comment this line the err return Z_OK, otherwise return Z_BUFF_ERROR.
ScopeGuard guard([&](){if (dstBuf) delete[] dstBuf; dstBuf=NULL;});

// zlib function. 
int err = uncompress((Bytef *)dstBuf, (uLongf*)&dstLen, (Bytef*)src, fileLen);

if (err != Z_OK)
{
    cout<<"uncompress error..."<<err<<endl;
    return false;
}`
6
  • The return value of function uncompress is Z_BUFF_ERR only when I run the code in centos g++ 4.8.5. when I annotate the ScopeGuard, It return Z_OK. Commented Jun 2, 2016 at 11:56
  • 1
    Also, CentOS is not a compiler; what's the actual compiler and its version? Commented Jun 2, 2016 at 11:56
  • When I run in centos with gcc version 4.8.5, the result is error. Commented Jun 2, 2016 at 11:59
  • When you say "annotate", do you mean "comment"? Commented Jun 2, 2016 at 12:02
  • Perhaps the call to new char[dstLen] fails in CentOS because you're requesting too much memory. Are you using the throwing version of new? Commented Jun 2, 2016 at 12:05

1 Answer 1

1

This is most likely because of this: (uLongf*)&dstLen.

dstLen is an int, which is 32 bits and all current typical systems. uLongf, however, is an alias for unsigned long, which is 32 bits on Windows and 32-bit *nix systems, but 64 bits on 64-bit *nix systems.

It is not safe, and likely to do the wrong thing, to cast an int* to an uLongf*.

The solution is to make dstLen an uLongf and remove the cast.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, thanks a lot! I solved the problem with this method.
The ubuntu is 32-bit,but centos is 64-bit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.