Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

Segmentation fault when trying to copy strings

Status
Not open for further replies.

mobile-it

Advanced Member level 1
Advanced Member level 1
Joined
Apr 24, 2004
Messages
464
Helped
22
Reputation
44
Reaction score
8
Trophy points
1,298
Activity points
3,344
#include <stdio.h>

int main(void){
char string[] = "hello\n";
char *p;
char *q;
q = string;


while(*p++=*q++)
;
printf("%s\n",q);
printf("%s\n",p);

return 0;
}

I get a segmentation fault when I try to run this program on ubuntu linux after compiled with gcc anyone knows the problem? I want to use this
Code:
 while(*p++=*q++)
;
instruction


thanks
 

Pointer p is uninitialized p==NULL;
*(NULL)=value; probably causes segmentation fault. Try adding line p=(char *)malloc(max_string_lenght);
 

    mobile-it

    Points: 2
    Helpful Answer Positive Rating
You are using the assignment operator '=', you need to use the logical equal operator '==' :

You should use *p++ == *q++

Plus the pointer p was never assigned a valid address so it's address is NULL. So the statement will give an error. But even if p was assigned a valid address, the *p++ = *q++ statement by definition is always true so it won't terminate until the pointer p is incremented until it gives an error or just wraps around the segment to address 0 and so on ad nauseum..
 

    mobile-it

    Points: 2
    Helpful Answer Positive Rating
Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top