Activity - pointers
Review the example stringcopy.c, excerpted below; it is buggy and triggers a segmentation fault!
- Copy the
stringcopy.c
program into your own directory, and compile it:cp /thayerfs/courses/22fall/cosc050/workspace/activities/day9/stringcopy.c . mygcc -o stringcopy stringcopy.c
- Explain the pointer notation used in the parameters.
- Explain the pointer notation used in the conditional.
- Explain what happens inside the loop.
- Why is there an assignment after the loop?
- Where is the bug in
main()
? - What might go wrong inside
stringcopy
?
#include <stdio.h>
#include <stdlib.h>
void stringcopy(char *sp, char *dp);
int main()
{
char *src = "CS 50";
char *dest = "";
// copy src to dest and print them out
stringcopy(src, dest);
printf("src = '%s'\n", src);
printf("dest = '%s'\n", dest);
return 0;
}
/* stringcopy - copy string from source sp to destination dp */
void stringcopy(char *sp, char *dp)
{
while (*sp != '\0') {
*dp++ = *sp++;
}
*dp = '\0';
}
This code causes a segfault when run. Explain why.