Knowee
Questions
Features
Study Tools

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);
}
🧐 Not the exact question you are looking for?Go ask a question

Solution

There are several issues with this code:

  1. The function cp is declared to return an int, but it doesn't return any meaningful value. It always returns 0, which usually indicates success. However, there's no way to indicate failure (for example, if malloc fails).

  2. 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.

  3. The pointer s is local to the function cp. Once the function returns, s goes out of scope and you lose the reference to the allocated memory. This is a memory leak.

  4. There's no error checking for the malloc call. If malloc fails, it returns NULL and the subsequent strcpy call would result in undefined behavior.

  5. 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.

This problem has been solved

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<

1/1

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.