DEV Community

Mukul Roy
Mukul Roy

Posted on • Edited on

πŸš€ C Challenge: Can you find the bug in this Pointer Logic? 🧠

Hello C Developers! πŸ‘‹

Let's test our debugging skills today. I’ve written a small piece of code that is supposed to swap two strings using pointers. However, it's not behaving as expected for everyone, or is it?
The Code:

include

// Function to swap two string pointers
void swap_strings(char **str1, char **str2) {
char *temp = *str1;
*str1 = *str2;
*str2 = temp;
}

int main() {
char *p1 = "Game";
char *p2 = "Changer";

printf("Before Swap: p1 = %s, p2 = %s\n", p1, p2);

// Attempting to swap
swap_strings(&p1, &p2);

printf("After Swap: p1 = %s, p2 = %s\n", p1, p2);

return 0;
Enter fullscreen mode Exit fullscreen mode

}

The Challenge:

Memory Safety: Does this code lead to a Segmentation Fault?

Pointer Logic: Are we swapping the actual content or just the memory addresses?

Best Practice: Why is using char *p = "String" considered risky compared to char p[] = "String" in this context?
Enter fullscreen mode Exit fullscreen mode

I’ve seen many beginners struggle with pointer-to-pointer logic and String Literals. Let's discuss in the comments! πŸ”Ž

c #programming #debugging #challenge #learning

Top comments (3)

Collapse
 
pauljlucas profile image
Paul J. Lucas

You need to learn to use Markdown and format your code correctly. To begin and end a code block, use 4 back-ticks on a line by themselves. For inline code, encode it between single back-ticks. Otherwise, your article is too hard to read.

Collapse
 
mukulroy profile image
Mukul Roy

Thanks for the feedback! You're absolutely rightβ€”proper formatting is essential for readability. I've updated the post with the correct code blocks and markdown. Appreciate you pointing that out and helping me improve the quality of my articles! πŸš€

Collapse
 
pauljlucas profile image
Paul J. Lucas

It's still wrong.