Question

Working on this little piece of code, but for some reason it keep crashing the whole time.

Anyone got an idea what i'm doing wrong

char *str;
printf("Enter a string\n");
gets(str);
printf("The size of the string is %d", strlen(str));
system("PAUSE");    
return 0;
Was it helpful?

Solution

You have not allocated any memory for str. Declare a buffer, for example char str[50], but be aware of buffer overflows.

OTHER TIPS

You only created an char* pointer which points to random space in memory and you try to do something with it - and that is why your program crashes.

You should create an array of chars:

char str[50];

or dynamically allocate memory for string with malloc:

char* str;
str = (char *)malloc(50*sizeof(char)); // allocate memory
// some operations
free(str);                      // deallocate memory

where 50 is your estimated size of buffer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top