?
Solved

Problems with zero termination

Posted on 2006-04-14
45
Medium Priority
?
502 Views
Last Modified: 2012-06-27
hello I try to zero terminate a char

char szBuffer[BUFFER_SIZE];
szBuffer[nRet-1]='\0'; // zero terminate the char so we know where it ends

But I get debug errors when running it
0
Comment
Question by:m-jansen
  • 31
  • 12
  • 2
45 Comments
 

Author Comment

by:m-jansen
ID: 16457331
nRet = recv(Socket, szBuffer, sizeof(szBuffer)-1, 0);
0
 

Author Comment

by:m-jansen
ID: 16457339
is it because another \0 is in another place in the char?
0
 
LVL 4

Expert Comment

by:chip3d
ID: 16457449
could you please post the error...

the error is surely not a other \0 in the string. Are you sure your nRet is not bigger than BUFFER_SIZE?

You can fill your whole buffer with 0 at initialization:
char szBuffer[BUFFER_SIZE] = {0};
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 11

Expert Comment

by:x4u
ID: 16457510
If you can't read anything from the socket nRet will be 0, thus szBuffer[nRet-1] will become szBuffer[-1] and probably cause problems.
0
 

Author Comment

by:m-jansen
ID: 16457512
nRet is smaler than the BUFFER_SIZE

Unhandled exception at 0x1022fb10 (msvcr80d.dll) in browser3.exe: 0xC0000005: Access violation reading location 0x00000004.

main_loop:
        mov     eax,dword ptr [ecx]     ; read 4 bytes
0
 

Author Comment

by:m-jansen
ID: 16457534
it looks like nRet has the value 377 when the error happens
0
 

Author Comment

by:m-jansen
ID: 16457542
#define BUFFER_SIZE = 1024
0
 
LVL 11

Expert Comment

by:x4u
ID: 16457549
>> Access violation reading location 0x00000004.
This looks like you are reading from a null pointer. Maybe you can run it in the debugger and see which line actually causes the access violation.
0
 

Author Comment

by:m-jansen
ID: 16457577
The debugger wont go into more depth I think
0
 

Author Comment

by:m-jansen
ID: 16457595
>If you can't read anything from the socket nRet will be 0, thus szBuffer[nRet-1] will become szBuffer[-1] and probably cause problems.

szBuffer[10]='\0'       \\ wont work either
0
 

Author Comment

by:m-jansen
ID: 16457622
>You can fill your whole buffer with 0 at initialization:
>char szBuffer[BUFFER_SIZE] = {0};
Does that empty the char? Because I wonder how to empty a char.
Like szBuffer = {0}?
0
 

Author Comment

by:m-jansen
ID: 16457658
From the debugger:
continue 1: szBuffer[nRet-1]      115 's'      char
continue 2: szBuffer[nRet-1]      34 '"'      char
and then it crash
0
 
LVL 4

Expert Comment

by:chip3d
ID: 16457692
i don't think that your szBuffer causes the crash. Could you post more code?

>Does that empty the char? Because I wonder how to empty a char.
it just can be done by initialisation. Else you can do this with a loop:
0
 

Author Comment

by:m-jansen
ID: 16457715
     int counter=0;
      while(1)
      {                                    
            // Wait to receive, nRet = NumberOfBytesReceived
            nRet = recv(Socket, szBuffer, sizeof(szBuffer)-1, 0);
            cout << "c: " << counter << " nRet: " << nRet <<endl;
            szBuffer[nRet-1]='\0'; // zero terminate the char so we know where it ends

            if (nRet == SOCKET_ERROR)
                  break;

            // fprintf(stderr,"\nrecv() returned %d bytes", nRet);

            // Did the server close the connection?
            if (nRet == 0)
                  break;
            
            // Remove the http host header and store the content to a file
            if (nRet !=0 || nRet != SOCKET_ERROR) {                  
                  if(counter==0) {
                        char* szBuffer_beginning1 = strstr(szBuffer, "\r\n\r\n") + 4;
                        WriteToFile(pszFile,(char*)szBuffer_beginning1);
                  }
                  if(counter==1) {
                        char* szBuffer_beginning2 = strstr(szBuffer, "\r\n\r\n") + 4;
                        WriteToFile(pszFile,(char*)szBuffer_beginning2);
                  }            
                  if(counter>1) {
                        WriteToFile(pszFile,(char*)szBuffer);
                  }
            }

            counter++;
      }
      closesocket(Socket);
0
 

Author Comment

by:m-jansen
ID: 16457762
Maybe there is another technique I should use instead of this. Feel free to tell me if you want.
0
 

Author Comment

by:m-jansen
ID: 16457829
My main problem is that the buffer sends to much data to the WriteToFile method when the received amount is smaller than the buffer... so in the end of the file I get a little to much.... hard to explain
0
 

Author Comment

by:m-jansen
ID: 16457835
The problem can be fixed by parsing the file on the disk, but I thought it would be great to parse it before it was written to the disk...
0
 
LVL 4

Expert Comment

by:chip3d
ID: 16457849
you don't need decrement nRet: zBuffer[nRet-1]='\0'; -> zBuffer[nRet]='\0'; because  of sizeof(szBuffer)-1 in your recv function call. nRet will max return BUFFER_SIZE -1;
What happens if nRet is == SOCKET_ERROR? This errorvalue is not greater than BUFFER_SIZE-1?

Are you debugging in releasemode?
0
 

Author Comment

by:m-jansen
ID: 16457856
>Else you can do this with a loop:
I tried to empty it with..
fill(szBuffer, szBuffer + sizeof(szBuffer), '\0');
But I get the same crash then..
0
 

Author Comment

by:m-jansen
ID: 16457860
#define SOCKET_ERROR = -1
0
 

Author Comment

by:m-jansen
ID: 16457872
>Are you debugging in releasemode?
I made a breakepoint here:
szBuffer[nRet-1]='\0'; // zero terminate the char so we know where it ends

And then I choosed Start debugging. After that I choosed continue two times and then it crashed. I don't really know what you mean about releasemode.
0
 
LVL 4

Expert Comment

by:chip3d
ID: 16457901
ok, if SOCKET_ERROR is -1, you have to check for this error before you call  szBuffer[nRet-1]='\0'.

do have some other breakpoints set?
just set after each instruction a breakpoint, to be sure the exception really happens directly after szBuffer[nRet-1]='\0'....
what compiler do you use?
0
 

Author Comment

by:m-jansen
ID: 16457913
I could observe what the szBuffer during debuggin...

continue 1: szBuffer[nRet-1]     115 's'     char
continue 2: szBuffer[nRet-1]     34 '"'     char

and then it crash
0
 

Author Comment

by:m-jansen
ID: 16457915
VC8-2005
0
 
LVL 4

Expert Comment

by:chip3d
ID: 16457940
>I don't really know what you mean about releasemode.
to the right of your startdebugging you can specifiy debug o relese mode... -> set to debug

after you get to your breakpoint the second time, use F10 to debug step by step through your code. I just wont to find out if it is really this line causing the exception. I can't be that nRet really is 115 or 34 and a exception is called
0
 

Author Comment

by:m-jansen
ID: 16457950
>just set after each instruction a breakpoint
hmm.. I've added breakpoints on all the lines occur here:

      while(1)
      {                                    

            // Wait to receive, nRet = NumberOfBytesReceived
            nRet = recv(Socket, szBuffer, sizeof(szBuffer)-1, 0);
            if (nRet == SOCKET_ERROR)
                  break;

            cout << "c: " << counter << " nRet: " << nRet <<endl;
            szBuffer[nRet]='\0'; // zero terminate the char so we know where it ends

            // fprintf(stderr,"\nrecv() returned %d bytes", nRet);

            // Did the server close the connection?
            if (nRet == 0)
                  break;
            
            // Remove the http host header and store the content to a file
            if (nRet !=0 || nRet != SOCKET_ERROR) {                  
                  if(counter==0) {
                        char* szBuffer_beginning1 = strstr(szBuffer, "\r\n\r\n") + 4;
                        WriteToFile(pszFile,(char*)szBuffer_beginning1);
                  }
                  if(counter==1) {
                        char* szBuffer_beginning2 = strstr(szBuffer, "\r\n\r\n") + 4;
                        WriteToFile(pszFile,(char*)szBuffer_beginning2); // ERROR in RED !!! +szBuffer_beginning2 0x00000004 <Bad Ptr>char *

                  }            
                  if(counter>1) {
                        WriteToFile(pszFile,(char*)szBuffer);
                  }
            }

            counter++;
      }
      closesocket(Socket);
0
 

Author Comment

by:m-jansen
ID: 16457977
It look like the error occur here first:

WriteToFile(pszFile,(char*)szBuffer_beginning2); // ERROR in RED !!! +szBuffer_beginning2 0x00000004 <Bad Ptr>char *

Then it crash
0
 

Author Comment

by:m-jansen
ID: 16457993
I can't run the in relese mode. Then VS tells me that there was built errors.
0
 

Author Comment

by:m-jansen
ID: 16457999
Error      1      error LNK2001: unresolved external symbol __imp__WSAStartup@8      CRetriveWebPage.obj      
Error      2      error LNK2001: unresolved external symbol __imp__WSACleanup@0      CRetriveWebPage.obj      
Error      3      error LNK2001: unresolved external symbol __imp__inet_addr@4      CRetriveWebPage.obj      
Error      4      error LNK2001: unresolved external symbol __imp__gethostbyname@4      CRetriveWebPage.obj      
Error      5      error LNK2001: unresolved external symbol __imp__gethostbyaddr@12      CRetriveWebPage.obj      
Error      6      error LNK2001: unresolved external symbol __imp__socket@12      CRetriveWebPage.obj      
Error      7      error LNK2001: unresolved external symbol __imp__getservbyname@8      CRetriveWebPage.obj      
Error      8      error LNK2001: unresolved external symbol __imp__htons@4      CRetriveWebPage.obj      
Error      9      error LNK2001: unresolved external symbol __imp__connect@12      CRetriveWebPage.obj      
Error      10      error LNK2001: unresolved external symbol __imp__closesocket@4      CRetriveWebPage.obj      
Error      11      error LNK2001: unresolved external symbol __imp__send@16      CRetriveWebPage.obj      
Error      12      error LNK2001: unresolved external symbol __imp__recv@16      CRetriveWebPage.obj      
Error      13      fatal error LNK1120: 12 unresolved externals      C:\Skole\semester4\Nettverk\sockets\browser3\Release\browser3.exe      
0
 
LVL 4

Accepted Solution

by:
chip3d earned 2000 total points
ID: 16458006
ok,

strstr retruns 0 if it can't find "\r\n\r\n", this means szBuffer_beginning2 = 0+4 -> this is not good, this is not a valid pointer and its not 0, this could cause a crash within WriteToFile.
Try
 char* szBuffer_beginning2 = strstr(szBuffer, "\r\n\r\n");
 if (szBuffer_beginning2 != 0)
    WriteToFile(pszFile,szBuffer_beginning2+4);

also change the code for szBuffer_beginning1
0
 

Author Comment

by:m-jansen
ID: 16458010
Only works in debug mode
0
 
LVL 4

Expert Comment

by:chip3d
ID: 16458012
error LNK2001: unresolved external symbol
could be a missing lib
0
 
LVL 4

Expert Comment

by:chip3d
ID: 16458030
check project->properties->Configuration Prop->Linker->Input->AdditionalDep
has the debug config some dependencies release don't have?
0
 

Author Comment

by:m-jansen
ID: 16458035
it doesn't crash now. what about the missing lib?
0
 

Author Comment

by:m-jansen
ID: 16458046
AdditionalDep: WS2_32.lib
0
 

Author Comment

by:m-jansen
ID: 16458049
AdditionalDep:
Inherited values:

kernel32.lib
user32.lib
gdi32.lib
winspool.lib
comdlg32.lib
advapi32.lib
shell32.lib
ole32.lib
oleaut32.lib
uuid.lib
odbc32.lib
odbccp32.lib
0
 
LVL 4

Expert Comment

by:chip3d
ID: 16458055
add WS2_32.lib to the release dependencies and try to compile in releasemode
0
 

Author Comment

by:m-jansen
ID: 16458078
I don't know where to add release dependencies... I've looked under Debuggin - Configuration-Release
0
 

Author Comment

by:m-jansen
ID: 16458080
...in project properties
0
 

Author Comment

by:m-jansen
ID: 16458087
btw:
Just want to say that the working code looks like this now:
      int counter=0;
      while(1)
      {                                    

            // Wait to receive, nRet = NumberOfBytesReceived
            nRet = recv(Socket, szBuffer, sizeof(szBuffer)-1, 0);      
            if (nRet == SOCKET_ERROR)
                  break;

            cout << "c: " << counter << " nRet: " << nRet <<endl;
            szBuffer[nRet]='\0'; // zero terminate the char so we know where it ends

            // fprintf(stderr,"\nrecv() returned %d bytes", nRet);

            // Did the server close the connection?
            if (nRet == 0)
                  break;
            
            // Remove the http host header and store the content to a file
            if (nRet !=0 || nRet != SOCKET_ERROR) {                  
                  if(counter==0) {
                        char* szBuffer_beginning1 = strstr(szBuffer, "\r\n\r\n");
                        if (szBuffer_beginning1 != 0)
                              WriteToFile(pszFile,szBuffer_beginning1+4);
                  }            
                  if(counter>0) {
                        WriteToFile(pszFile,(char*)szBuffer);
                  }
            }

            counter++;
      }
      closesocket(Socket);
0
 
LVL 4

Expert Comment

by:chip3d
ID: 16458097
add them there project->properties->Configuration Prop->Linker->Input->AdditionalDep
but switch to release before you open the project->properties

You also can switch in the properties dialog. upper left: Configuration - combobox
0
 

Author Comment

by:m-jansen
ID: 16458113
That did the trick. I've learned a lot now. Thank you very much.
0
 
LVL 4

Expert Comment

by:chip3d
ID: 16458130
i think if (nRet !=0 || nRet != SOCKET_ERROR)  should be if (nRet !=0 && nRet != SOCKET_ERROR)
in this case you can delete this line cuz you ceckt both cases before and break the loop if they fail
     int counter=0;
     while(1)
     {                              

          // Wait to receive, nRet = NumberOfBytesReceived
          nRet = recv(Socket, szBuffer, sizeof(szBuffer)-1, 0);    
          if (nRet == SOCKET_ERROR)
               break;

          cout << "c: " << counter << " nRet: " << nRet <<endl;
          szBuffer[nRet]='\0'; // zero terminate the char so we know where it ends

          // fprintf(stderr,"\nrecv() returned %d bytes", nRet);

          // Did the server close the connection?
          if (nRet == 0)
               break;
         
          // Remove the http host header and store the content to a file          
          if(counter==0) {
               char* szBuffer_beginning1 = strstr(szBuffer, "\r\n\r\n");
               if (szBuffer_beginning1 != 0)
                    WriteToFile(pszFile,szBuffer_beginning1+4);
          }          
          if(counter>0) {
               WriteToFile(pszFile,(char*)szBuffer);
          }


          counter++;
     }
     closesocket(Socket);
0
 
LVL 4

Expert Comment

by:chip3d
ID: 16458143
np :)
0
 

Author Comment

by:m-jansen
ID: 16458186
Thanks again :)
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question