Why buffer no work int countValidWords(char* s) { char* buffer = malloc(strlen(s) *…
Private research annotation
Sign in to add a private research label or note.
- User
Why buffer no work
int countValidWords(char* s) { char* buffer = malloc(strlen(s) * sizeof(char)); printf("%d %d", strlen(s), strlen(buffer));
cpp
- Assistant
The issue arises because
mallocallocates uninitialized memory forbuffer, so the memory content is indeterminate. When you attempt to usestrlen(buffer), it will read memory until it encounters a null termination character (\0). Without initializingbuffer,strlen(buffer)can result in undefined behavior since the content ofbufferis effectively random.Here's a description of the problems and how you might address them: