What is the safest way to pass strings around in C?

Posted by chucknelson on Stack Overflow See other posts from Stack Overflow or by chucknelson
Published on 2010-04-15T00:00:53Z Indexed on 2010/04/15 0:03 UTC
Read the original article Hit count: 244

Filed under:
|
|

I have a program in C using Solaris with VERY ancient compatibility it seems. Many examples, even here on SO, don't work, as well as lots of code I've written on Mac OS X.

So when using very strict C, what is the safest way to pass strings?

I'm currently using char pointers all over the place, due to what I thought was simplicity. So I have functions that return char*, I'm passing char* to them, etc.

I'm already seeing strange behavior, like a char* I passed having its value right when I enter a function, and then the value being mysteriously gone OR corrupted/overwritten after something simple like one printf() or an malloc to some other pointer.

I was thinking maybe declaring a local char[] inside each function, using strcpy() immediately, and then eventually returning a pointer where char *returnval = strdup(localchar[]);

This seems...sloppy. Can anyone point me in the right direction on a simple requirement?

© Stack Overflow or respective owner

Related posts about c

    Related posts about pointers