Question

Problems with zero termination

Asked by: m-jansen

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

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2006-04-14 at 13:52:45ID21814539
Topic

C++ Programming Language

Participating Experts
2
Points
500
Comments
45

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Strange buffer problem in release build
    Hi, In debug mode, the following line works properly. In release mode it does not. char szBuffer[256] int nBytesRead=myFile.Read(szBuffer, sizeof( szBuffer ) ); Any thoughts? When I check the size of the returned buffer, in both release and debug, it is 256. The file bei...
  2. urgent:debug async wininet
    Dear all, Here is my program.I don't know why it has error after download the resource from the Url.I will double the mark if you can debug it within one day.(it is a win32 console application) #include <windows.h> #include <iostream.h> #include <string.h&g...
  3. char buffer to CString
    Hi Experts, Sorry for the basic questions, but I am really new to C++ I am having the following problem: When I read a file into a buffer, and later that buffer is given to a CString, the program has some "unhandled exceptions". But not all the times, and not in th...
  4. unsigned char's
    hey, I havent used unsigned char's a lot but need to get something finished fast so dont have the time to get aquanted... I have an app that is a text to speach simulator and I need to concatenate sounds to create a word. The sound data is stored with unsigned char's(BYTE*)...
  5. Best way to null-terminate a char*
    I run a char * through an encoding routine and want to ensure that the char* has a null at the end. CBase b; CFile cinFile; char *inBuf = (char*)malloc(cinFile.GetLength()); char* outBuf; b.CreateMatchingEncodingBuffer(cinFile.GetLength(), &outBuf); unsigned int numByt...
  6. char* & string
    Hi experts, how do I fix the following code ? thanks. ----------------------------------- #include "stdafx.h" #include <iostream> #include <string> #include <math.h> using namespace std; int main(int argc, char* argv[]) { string a = &quo...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: m-jansenPosted on 2006-04-14 at 14:14:50ID: 16457331

nRet = recv(Socket, szBuffer, sizeof(szBuffer)-1, 0);

 

by: m-jansenPosted on 2006-04-14 at 14:15:54ID: 16457339

is it because another \0 is in another place in the char?

 

by: chip3dPosted on 2006-04-14 at 14:29:51ID: 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};

 

by: x4uPosted on 2006-04-14 at 14:36:55ID: 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.

 

by: m-jansenPosted on 2006-04-14 at 14:37:16ID: 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

 

by: m-jansenPosted on 2006-04-14 at 14:40:12ID: 16457534

it looks like nRet has the value 377 when the error happens

 

by: m-jansenPosted on 2006-04-14 at 14:41:24ID: 16457542

#define BUFFER_SIZE = 1024

 

by: x4uPosted on 2006-04-14 at 14:42:22ID: 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.

 

by: m-jansenPosted on 2006-04-14 at 14:47:07ID: 16457577

The debugger wont go into more depth I think

 

by: m-jansenPosted on 2006-04-14 at 14:49:28ID: 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

 

by: m-jansenPosted on 2006-04-14 at 14:53:16ID: 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}?

 

by: m-jansenPosted on 2006-04-14 at 14:59:14ID: 16457658

From the debugger:
continue 1: szBuffer[nRet-1]      115 's'      char
continue 2: szBuffer[nRet-1]      34 '"'      char
and then it crash

 

by: chip3dPosted on 2006-04-14 at 15:05:08ID: 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:

 

by: m-jansenPosted on 2006-04-14 at 15:09:56ID: 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);

 

by: m-jansenPosted on 2006-04-14 at 15:21:14ID: 16457762

Maybe there is another technique I should use instead of this. Feel free to tell me if you want.

 

by: m-jansenPosted on 2006-04-14 at 15:36:36ID: 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

 

by: m-jansenPosted on 2006-04-14 at 15:38:39ID: 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...

 

by: chip3dPosted on 2006-04-14 at 15:43:21ID: 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?

 

by: m-jansenPosted on 2006-04-14 at 15:45:12ID: 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..

 

by: m-jansenPosted on 2006-04-14 at 15:47:29ID: 16457860

#define SOCKET_ERROR = -1

 

by: m-jansenPosted on 2006-04-14 at 15:51:29ID: 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.

 

by: chip3dPosted on 2006-04-14 at 15:57:19ID: 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?

 

by: m-jansenPosted on 2006-04-14 at 16:00:08ID: 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

 

by: m-jansenPosted on 2006-04-14 at 16:00:45ID: 16457915

VC8-2005

 

by: chip3dPosted on 2006-04-14 at 16:09:09ID: 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

 

by: m-jansenPosted on 2006-04-14 at 16:10:57ID: 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);

 

by: m-jansenPosted on 2006-04-14 at 16:18:04ID: 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

 

by: m-jansenPosted on 2006-04-14 at 16:21:41ID: 16457993

I can't run the in relese mode. Then VS tells me that there was built errors.

 

by: m-jansenPosted on 2006-04-14 at 16:22:51ID: 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      

 

by: chip3dPosted on 2006-04-14 at 16:24:05ID: 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

 

by: m-jansenPosted on 2006-04-14 at 16:24:44ID: 16458010

Only works in debug mode

 

by: chip3dPosted on 2006-04-14 at 16:25:37ID: 16458012

error LNK2001: unresolved external symbol
could be a missing lib

 

by: chip3dPosted on 2006-04-14 at 16:29:20ID: 16458030

check project->properties->Configuration Prop->Linker->Input->AdditionalDep
has the debug config some dependencies release don't have?

 

by: m-jansenPosted on 2006-04-14 at 16:30:45ID: 16458035

it doesn't crash now. what about the missing lib?

 

by: m-jansenPosted on 2006-04-14 at 16:34:21ID: 16458046

AdditionalDep: WS2_32.lib

 

by: m-jansenPosted on 2006-04-14 at 16:35:30ID: 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

 

by: chip3dPosted on 2006-04-14 at 16:37:12ID: 16458055

add WS2_32.lib to the release dependencies and try to compile in releasemode

 

by: m-jansenPosted on 2006-04-14 at 16:44:10ID: 16458078

I don't know where to add release dependencies... I've looked under Debuggin - Configuration-Release

 

by: m-jansenPosted on 2006-04-14 at 16:44:44ID: 16458080

...in project properties

 

by: m-jansenPosted on 2006-04-14 at 16:48:07ID: 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);

 

by: chip3dPosted on 2006-04-14 at 16:50:58ID: 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

 

by: m-jansenPosted on 2006-04-14 at 16:53:40ID: 16458113

That did the trick. I've learned a lot now. Thank you very much.

 

by: chip3dPosted on 2006-04-14 at 16:56:54ID: 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);

 

by: chip3dPosted on 2006-04-14 at 17:01:01ID: 16458143

np :)

 

by: m-jansenPosted on 2006-04-14 at 17:14:29ID: 16458186

Thanks again :)

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...