Pointer problem

M

Min-Koo Seo

I'm using Linux gcc.

Follwing program raise segmentation fault.

#include<stdio.h>
#include<string.h>


void string_or(char *str1, char *str2)
{
int i;
int len = strlen(str1);
for (i = 0 ; i < len ; i++)
{
if (str2 == '1') {
str1 = str2;
}
}
}

int main() {

char *str1="00000001000";
char *str2="00000000001";

string_or(str1, str2);
printf("result=%s\n", str1);
}


However, if I use

int main() {

char str1[]="00000001000"; // Note that I've used [], instead of *
char str2[]="00000000001";

string_or(str1, str2);
printf("result=%s\n", str1);
}


Then, the function works perfectly.

What's the problem with '*'?
 
E

Emmanuel Delahaye

In said:
I'm using Linux gcc.

Follwing program raise segmentation fault.

Thanks your system for that.
#include<stdio.h>
#include<string.h>

void string_or(char *str1, char *str2)

This prototype suggests that the data pointed by both str1 and str2 might be
modified.
{
int i;
int len = strlen(str1);
for (i = 0 ; i < len ; i++)
{
if (str2 == '1') {
str1 = str2;
}
}
}


Actually, only str1 is modified. A better prototype could be:

void string_or(char *str1, char const *str2)
int main() {

char *str1="00000001000";
char *str2="00000000001";

string_or(str1, str2);
printf("result=%s\n", str1);
}


However, if I use

int main() {

char str1[]="00000001000"; // Note that I've used [], instead of *
char str2[]="00000000001";

string_or(str1, str2);
printf("result=%s\n", str1);
}

Then, the function works perfectly.

What's the problem with '*'?

Writing to a string literal causes an undefined behaviour. Anything can
occur. The segmentation fault is one of them, but a silent behaviour (the
most dangerous) could happen too. An undefined behaviour is an extremely
dangerous and vicious bug.

Don't do that. It's considered good practice to define a string litteral as
'read-only':

char const *str1 = "00000001000";

The parameter of the function being 'char *str1', a decent and well tuned
compiler or lint should emit a warning.

The second solution is an array of char initialized by a string litteral.
It's fine if you want to modify the string.

In you case, str1 must be a modifiable array of char,

char str1[] = "00000001000";

an str2 can be any of

or
char *str2="00000000001";
char const *str2="00000000001";
char str2[]="00000000001";
char const str2[]="00000000001";
 

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
474,266
Messages
2,571,082
Members
48,773
Latest member
Kaybee

Latest Threads

Top