What is wrong with this code:int cp(void){ char *s; s = malloc(12); strcpy(s, "Best School"); return (0);}
Question
What is wrong with this code:
int cp(void) {
char *s;
s = malloc(12);
strcpy(s, "Best School");
return (0);
}
Solution
There are several issues with this code:
-
The function
cpis declared to return anint, but it doesn't return any meaningful value. It always returns0, which usually indicates success. However, there's no way to indicate failure (for example, ifmallocfails). -
The string "Best School" is 11 characters long, but you also need space for the null terminator (
\0), which makes it 12 characters long. So, you need to allocate 13 bytes of memory, not 12. -
The pointer
sis local to the functioncp. Once the function returns,sgoes out of scope and you lose the reference to the allocated memory. This is a memory leak. -
There's no error checking for the
malloccall. Ifmallocfails, it returnsNULLand the subsequentstrcpycall would result in undefined behavior. -
The allocated memory is not freed, which leads to a memory leak.
Here's a corrected version of the function:
#include <stdlib.h>
#include <string.h>
int cp(char **out) {
char *s = malloc(13);
if (s == NULL) {
return -1;
}
strcpy(s, "Best School");
*out = s;
return 0;
}
In this version, the function takes a pointer to a pointer to char. It allocates memory and copies the string into the new memory. If everything is successful, it stores the pointer to the new string in *out and returns 0. If malloc fails, it returns -1. The caller is responsible for freeing the memory when it's no longer needed.
Similar Questions
What is the output of the following code?char str1[] = "C programming";char str2[20];strcpy(str2, str1);printf("%s\n", str2);
What is the output of the following C code?char *ptr;char mystring[] = "abcdefg";ptr = myString;ptr += 5;
Which of the library function put back the length of a string?a.strlenb.strcatc.strcmpd.strcpy
Problem statementSend feedbackint a = 7;int b = 17;int *c = &b;*c = 7;cout << a << " “ << b << endl;
What will be print after executing following statement int value=65; char ch=value; cout<
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.