Passing strings directly to functions

Is it wrong to use direct string passing in functions?

Will this lead to memory errors?

func(char *x) {
   //do stuff
}

func("String");

      

Or is it safer to do it?

char *s = "string";
func(s);

      

+3


source to share


2 answers


Will this lead to memory errors?

Maybe if you try to change this line.

To be sure, declare your function

func(const char *x) {

      

But there is nothing wrong with passing string literals to functions. Otherwise 99.99 programs are poorly written.



Or is it safer to do it?

char *s = "string";
func(s);

      

This doesn't change anything since you are passing a pointer to the same string literal

But the code below is safe as you are allocating RW (read / write) memory to accommodate the string and the system copies this literal to that allocated space

 char s[] = "string";
 func(s);

      

+4


source


func(char *x) {
   //do stuff
}

      

this function takes a pointer to a string as input. The interface allows reading and writing with x

sharpened data.

but since you are using a string literal (in both cases of your examples) it is illegal to change the memory of that string literal (and most ex compilers gcc

organize code / data in a way that prevents you from doing this: SEGV)

The "safe" way (as long as you don't go beyond the string constraints when writing, or of course you read):



char s[] = "string";
func(s);

      

or if you don't plan on changing the content s

in func

, declare the pointer as const

:

func(const char *x)

      

+2


source







All Articles