1

I have a piece of code which works well in debug mode in visual studio but crashes in release mode. After a lot of guess work, i found the piece of code which is causing the crash.

char *buff ="some random text";
char *temp = NULL;
char *pos = NULL;
int len = strlen("random text");

pos = strstr(buff,"random");
temp = (char *) malloc(len+1);
memset(temp,0,len+1);
memcpy(temp,pos,len);

This works perfectly in debug mode, but crashes in release. Could any one point out the error ?

user1692342
  • 5,007
  • 11
  • 69
  • 128
  • 1
    I checked this piece of code in visual studio 2010 in both Debug mode and Release mode... It works perfectly. I assume that you doubt this piece of code in a large program.. I have to say, this part is not creating the trouble – hazzelnuttie Jun 19 '13 at 06:31
  • have you "free" the pointer allocated – hazzelnuttie Jun 19 '13 at 06:32
  • @hazzelnuttie I fixed the problem, I was doing at a place above this code, strlen(temp+3) instead of strlen(temp)+3 !! – user1692342 Jun 19 '13 at 06:36

3 Answers3

2

The code section shown looks fine.As an addition with unwind's answer.Possible reasons of failing may be

1)uninitialised variables

2)the preprocessor symbols _DEBUG and NDEBUG. If you have any code inside an #ifdef _DEBUG / #endif block.

3)compiler optimisation

Dayal rai
  • 6,548
  • 22
  • 29
  • did you try after turning off optimization? – Dayal rai Jun 19 '13 at 06:17
  • 2
    so better you start debugging in release mode.you can debug a release build. Just go to 'Project -> Settings', choose the Win32 Release configuration, tab 'C/C++', 'General' and set 'Debug Info' to 'Program Database'. Then go to the tab 'Linker', and turn on 'Generate Debug Info'. If you rebuild your project now, you will be able to run it in the debugger. Regardless of whether your program crashes or just doesn't behave as expected, running it in the debugger will show you why. – Dayal rai Jun 19 '13 at 06:22
  • i found the problem, I was doing at a place above this code, strlen(temp+3) instead of strlen(temp)+3 !! Thanks for ur help – user1692342 Jun 19 '13 at 06:37
1

It looks legit, a few minor nitpicks as usual:

  1. Don't cast the return value of malloc() in C.
  2. Use more const: buff, pos and len should all be declared const.
  3. Most importantly, check the return value of malloc() before accessing the memory.
Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606
-1

When you use malloc try

temp  = malloc((len + 1) *sizeof(*temp));
Alexis
  • 2,149
  • 2
  • 25
  • 39