Hi,

I dont know why I am getting segmentation fault when adding the line 'int n'

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{

   char* pStr; // no memory allocation
int n;

	printf("enter a string\n");
	fgets(pStr,20,stdin);
    printf("\nvalue of string is %s\n",pStr);

while(*pStr!='\0')
	{
 printf("value of string is %c\n",*pStr);
*pStr++;


}

return 0;

}

Dani AI

Generated

The crash was not caused by adding int n itself — it was a symptom of undefined behavior from using an uninitialised pointer. Declaring a local pointer like the one in the first post does not allocate storage. Reading or writing through that pointer (for example with fgets) writes into indeterminate memory and can behave differently when you change local variables: adding int n changes the stack layout and can make the program crash where it previously "worked." was right to point out allocation, and was right that a declaration alone does not reserve space.

Safe options (examples):

char buf[128];
if (fgets(buf, sizeof buf, stdin) != NULL) {
    char *it = buf;
    while (*it) {
        printf("value of string is %c\n", *it);
        ++it;
    }
}

Or, when you need a dynamic buffer:

char *s = malloc(200);
if (s == NULL) { perror("malloc"); exit(1); }
if (fgets(s, 200, stdin) != NULL) {
    for (char *it = s; *it; ++it) putchar(*it);
}
free(s);

A few practical notes and gotchas:

  • Pointer increment precedence: *(ptr++) increments the pointer; (*ptr)++ increments the character. Use a separate iterator (it) if you need to preserve the original pointer for free(). Example pattern:
char *base = s;
for (char *it = base; *it; ++it) putchar(*it);
free(base);
  • Always check fgets (returns NULL on EOF/error) and malloc (NULL on failure).
  • Compile with warnings and sanitizers to catch issues early, e.g. gcc -Wall -Wextra -g and try AddressSanitizer (-fsanitize=address) or run under Valgrind.

These checks remove the undefined behavior that caused the mysterious segmentation fault when you added int n.

Recommended Answers

All 4 Replies

Your code doesn't seems to work in my compiler Dev C++, with or without int n.
which compiler are you using.?

Your using a character pointer that hasn't been initialized. Line 8 should be

char* pStr = (char*)malloc(200 * sizeof(char));
/*check allocation here*/

Thanks gerard

char *pStr;

means there is not any allocation in memory rather its just a declaration.

Thanks gerard, the program works fine now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.