Solved

String memory problem

Posted on 1998-04-17
3
206 Views
Last Modified: 2010-04-15
Hi,

If I have:

char msgbuf[1024];

and msgbuf contains something lets say "--ABCDEF";

Now in my program I do the following:

 while((msgbuf[0] != '-') &&(msgbuf[1] != '-') &&(strcmp((strdup(msgbuf+2)),newboundvalue)))

/*Where newboundvalue is "ABCDEF"  */

Now my question is :
strdup() returns a pointer to a new string that is a  dupli-
     cate  of the string pointed to by s1.The space for the new string is obtained using malloc(3C). (Source : Man pages)
Now how do I free  this memory ??? Because when I run purify
it says there is a memory leak due to the strdup command.

Any help will be appreciated.

Thanks
0
Comment
Question by:singhtaj
3 Comments
 
LVL 4

Accepted Solution

by:
piano_boxer earned 50 total points
ID: 1249465
First you need to store the pointer returnet from strdup

Modify the while-line to something like this:

char* pStr;
while((msgbuf[0] != '-') &&(msgbuf[1] != '-') &&(strcmp((pStr = strdup(msgbuf+2)),newboundvalue)))
{
    free(pStr);
    [.......]
}


0
 
LVL 84

Expert Comment

by:ozo
ID: 1249466
Why are you using strdup at all if you're not going to be keeping the new string?
Why not just strcmp(msgbuf+2,newboundvalue)?
0
 

Author Comment

by:singhtaj
ID: 1249467
Good Idea!!!

Thanks

0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.

760 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

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now