Link to home
Start Free TrialLog in
Avatar of m-jansen
m-jansen

asked on

Problems with zero termination

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
Avatar of m-jansen
m-jansen

ASKER

nRet = recv(Socket, szBuffer, sizeof(szBuffer)-1, 0);
is it because another \0 is in another place in the char?
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};
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.
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
it looks like nRet has the value 377 when the error happens
#define BUFFER_SIZE = 1024
>> 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.
The debugger wont go into more depth I think
>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
>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}?
From the debugger:
continue 1: szBuffer[nRet-1]      115 's'      char
continue 2: szBuffer[nRet-1]      34 '"'      char
and then it crash
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:
     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);
Maybe there is another technique I should use instead of this. Feel free to tell me if you want.
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
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...
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?
>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..
#define SOCKET_ERROR = -1
>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.
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?
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
VC8-2005
>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
>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);
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
I can't run the in relese mode. Then VS tells me that there was built errors.
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      
ASKER CERTIFIED SOLUTION
Avatar of chip3d
chip3d
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Only works in debug mode
error LNK2001: unresolved external symbol
could be a missing lib
check project->properties->Configuration Prop->Linker->Input->AdditionalDep
has the debug config some dependencies release don't have?
it doesn't crash now. what about the missing lib?
AdditionalDep: WS2_32.lib
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
add WS2_32.lib to the release dependencies and try to compile in releasemode
I don't know where to add release dependencies... I've looked under Debuggin - Configuration-Release
...in project properties
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);
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
That did the trick. I've learned a lot now. Thank you very much.
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);
np :)
Thanks again :)