Reputation: 127
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;
Upvotes: 0
Views: 1457
Reputation: 517
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.
Upvotes: 2
Reputation: 8343
You have not allocated any memory for str
. Declare a buffer, for example char str[50]
, but be aware of buffer overflows.
Upvotes: 3