-2

I am getting this error while solving problem(217.Contains Duplicate) on leetcode

AddressSanitizer:DEADLYSIGNAL
=================================================================
==33==ERROR: AddressSanitizer: stack-overflow on address 0x7ffed3a8f0d8 (pc 0x0000003454ba bp 0x7fff8d5591f0 sp 0x7ffed3a8f0e0 T0)
    #2 0x7f8de24cc0b2  (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
==33==ABORTING

This is my code:

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        long long int n=2*1e9+10;
        long long int hsh[n];
        for (int i=0;i<sizeof(nums);++i){
            hsh[nums[i]+n]++;
        }
        int ok=0;
        for(int i=0;i<n;++i){
            if(hsh[i]>1){
                ok=1;
                break;
            }
        }
        if(ok==1){return true;}
        else{return false;}
    }
};
  • 1
    `sizeof(nums)` is absolutely wrong and should be `nums.size()` instead – UnholySheep Dec 21 '21 at 20:56
  • 2
    Looks like you are coming into C++ with a background in another language. You don't have to go full Yoda and unlearn what you have learned, but you will have to dedicate some time to learning how to do things the C++ way. You won't get that from a judge program at a competition site. I strongly recommend a [few good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – user4581301 Dec 21 '21 at 21:01
  • Side note: `long long int hsh[n];` is only legal in Standard C++ if `n` is a constant known at compile time. `long long int n=2*1e9+10;` technically isn't, so unless you change it to something like `constexpr long long int n=2*1e9+10;`, you'll get compiler errors when building with tools that do not support [Variable Length Arrays](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard). Note that making `n` constant will not solve that it's too large a number. – user4581301 Dec 21 '21 at 21:06

1 Answers1

3

hsh is too big for the stack. Use std::vector.

This is also wrong: sizeof(nums). You want nums.size().

bolov
  • 72,283
  • 15
  • 145
  • 224