strsep without modifying original buffer

R

Ram

Hi,

is it possible to implement strsep without modifying original buffer?

for Ex:

buf = malloc(30);
if (buf == NULL) {
DEBUG_PRINT("\nCould'nt allocate memory block @ %s:%d",
__FILE__, __LINE__);
return -1;
}

elem = strsep(&buf, ",");

I don't want disturb original 'buf' in this case..

please help me!

Thanks in advance,
Rammohan
 
R

Ram

Then why are you calling strsep?

What is it that you do want to happen?

Hi,

when i try to free() the buf, my device crashes becos it's trying to
free the memory which is not with in process heap area which this
process allocated...

it rarely happens, becos strsep() is disturbing initial pointer
address.. when i try to free() it and if the modified pointer address
out of process space.. free() will crash.. that's what happening
exactly in my case..

please provide any ideas to solve it..
Thanks,
Ram
 
R

Ram

     buf = malloc(30);
     p = buf;
     elem = strsep(&p, ",");
     free(buff);

Hi Pete,

Thanks for your response.. But sorry, the problem i am facing with
same implementation as you posted..

please correct me if i am wrong.. we are passing address of original
pointer to temporary pointer.. in this cases the starting address of
originally malloced pointer will also changes.. So we are not freeing
original address of malloced pointer..

once again thanks!
Ram
 
S

Seebs

please correct me if i am wrong.. we are passing address of original
pointer to temporary pointer.. in this cases the starting address of
originally malloced pointer will also changes.. So we are not freeing
original address of malloced pointer..

You are wrong. strsep() in this case will modify p, but it will not
modify buf, because p and buf are separate pointers. You do need to save
a copy of the original pointer to free, so if you're using strsep, use
a temporary pointer.

If you don't want to walk through the pointer, you probably shouldn't be
using strsep(). You might be able to use strtok() in this case (or strtok_r()
on a system where that exists and matters). Or strchr().

-s
p.s.: I believe strsep() is an extension common to BSD and Linux systems,
but didn't make it into the standard. One of the few things I think C99 got
wrong.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top