Delonous
Delonous

Reputation: 201

Passing strings directly into functions

Is it bad practice to directly pass strings into functions?

Will it cause memory errors?

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

func("String");

Or is it safer to do this?

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

Upvotes: 3

Views: 104

Answers (2)

0___________
0___________

Reputation: 67516

Will it cause memory errors?

It might if you try to modify this string.

To be safe declare your function

func(const char *x) {

But there is nothing wrong in passing string literals to the functions. Otherwise 99.99 of programs are badly written.

Or is it safer to do this?

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

It does not change anything as you pass the pointer to the same string literal

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

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

Upvotes: 4

Jean-François Fabre
Jean-François Fabre

Reputation: 140178

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

this function takes a pointer on a string as input. The interface allows to read & write from x pointed data.

but since you're using a string literal (in both cases of your examples), it's illegal to modify the memory of this string literal (and most compilers, ex gcc organize code/data in a way that prevents you from doing that: SEGV)

The "safe" way (as long as you don't go out of string bounds when writing - or reading of course -):

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

or if you're not planning to modify the contents of s in func, declare the pointer as const:

func(const char *x)

Upvotes: 2

Related Questions