CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jul 2005
    Posts
    1,030

    Why is there an exception?

    Here is the code,
    Code:
    bool isRotational(char* s1, char* s2)
    {
    	int len = strlen(s1);
    	char* s = new char[2 * len + 1];
    	char* p = s1;
    	char* q = s;
    
    	while (*p)
    	{
    		*s++ = *p++;
    	}
    
    	p = s1;
    
    	while (*p)
    	{
    		*s++ = *p++;
    	}
    	
    	*s = '\0';
    
    	int len2 = strlen(s2);
    	int j;
    	for (int i = 0; i<2 * len - len2 + 1; ++i)	
    	{
    		for (j = 0; j < len2 && q[i + j] == s2[j]; ++j);
    
    		if (j == len2)
    			return true;
    	}
    
    	delete[] s;
    	return false;
    }
    I randomly found that the exception is caused by the statement delete[] s. But when I debug this code, the debugger won't point to the statement delete[] s at all. So I am just wondering how'd I find out the exception is caused by that? Secondly why is there an exception in the code that looks innocent? Thanks!

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    Re: Why is there an exception?

    Code:
    delete []  s;
    What is "s" pointing to ? many times you increment the value of s.

  3. #3
    Join Date
    Jul 2005
    Posts
    1,030

    Re: Why is there an exception?

    Quote Originally Posted by Philip Nicoletti View Post
    Code:
    delete []  s;
    What is "s" pointing to ? many times you increment the value of s.
    I got it. Thanks. How am I able to debug such error? It seems the debugger won't point to the correct statement when such exception is thrown.

  4. #4
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Why is there an exception?

    Quote Originally Posted by LarryChen
    How am I able to debug such error? It seems the debugger won't point to the correct statement when such exception is thrown.
    Read Stroustrup's answer to the FAQ How do I deal with memory leaks? The executive summary: use a std::string or a container like std::vector instead of doing manual memory management.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured