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
m-jansenAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

 
m-jansenAuthor Commented:
nRet = recv(Socket, szBuffer, sizeof(szBuffer)-1, 0);
0
 
m-jansenAuthor Commented:
is it because another \0 is in another place in the char?
0
 
chip3dCommented:
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
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

 
x4uCommented:
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
 
m-jansenAuthor Commented:
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
 
m-jansenAuthor Commented:
it looks like nRet has the value 377 when the error happens
0
 
m-jansenAuthor Commented:
#define BUFFER_SIZE = 1024
0
 
x4uCommented:
>> 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
 
m-jansenAuthor Commented:
The debugger wont go into more depth I think
0
 
m-jansenAuthor Commented:
>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
 
m-jansenAuthor Commented:
>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
 
m-jansenAuthor Commented:
From the debugger:
continue 1: szBuffer[nRet-1]      115 's'      char
continue 2: szBuffer[nRet-1]      34 '"'      char
and then it crash
0
 
chip3dCommented:
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
 
m-jansenAuthor Commented:
     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
 
m-jansenAuthor Commented:
Maybe there is another technique I should use instead of this. Feel free to tell me if you want.
0
 
m-jansenAuthor Commented:
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
 
m-jansenAuthor Commented:
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
 
chip3dCommented:
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
 
m-jansenAuthor Commented:
>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
 
m-jansenAuthor Commented:
#define SOCKET_ERROR = -1
0
 
m-jansenAuthor Commented:
>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
 
chip3dCommented:
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
 
m-jansenAuthor Commented:
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
 
m-jansenAuthor Commented:
VC8-2005
0
 
chip3dCommented:
>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
 
m-jansenAuthor Commented:
>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
 
m-jansenAuthor Commented:
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
 
m-jansenAuthor Commented:
I can't run the in relese mode. Then VS tells me that there was built errors.
0
 
m-jansenAuthor Commented:
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
 
chip3dCommented:
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

Experts Exchange Solution brought to you by ConnectWise

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
 
m-jansenAuthor Commented:
Only works in debug mode
0
 
chip3dCommented:
error LNK2001: unresolved external symbol
could be a missing lib
0
 
chip3dCommented:
check project->properties->Configuration Prop->Linker->Input->AdditionalDep
has the debug config some dependencies release don't have?
0
 
m-jansenAuthor Commented:
it doesn't crash now. what about the missing lib?
0
 
m-jansenAuthor Commented:
AdditionalDep: WS2_32.lib
0
 
m-jansenAuthor Commented:
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
 
chip3dCommented:
add WS2_32.lib to the release dependencies and try to compile in releasemode
0
 
m-jansenAuthor Commented:
I don't know where to add release dependencies... I've looked under Debuggin - Configuration-Release
0
 
m-jansenAuthor Commented:
...in project properties
0
 
m-jansenAuthor Commented:
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
 
chip3dCommented:
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
 
m-jansenAuthor Commented:
That did the trick. I've learned a lot now. Thank you very much.
0
 
chip3dCommented:
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
 
chip3dCommented:
np :)
0
 
m-jansenAuthor Commented:
Thanks again :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.