-1

Trying to understand what's wrong with the following code:

int main (void){
    char *s;
    s=(char*)malloc(15);
    s="Hello World";
    free(s);
    return 0;
}

2 Answers2

3

s="Hello World"; does not copy the string into s. It changes the value of s to point to the string (technically the first character of the string).

Then s is no longer pointing to the memory allocated by malloc, so passing its new value to free is wrong because it asks free to release something that malloc never allocated.

In C source code, a string in quotation marks is a string literal. It results in the creation of an array of characters containing the characters from the source code, terminated by a null character. The memory for that array is reserved when the program starts executing and remains reserved for all of program execution. (This is called static storage duration and is separate from the allocated memory provided by malloc.)

Whenever an array is used in an expression other than the operand of sizeof or of unary & or as a string literal used to initialize in array (in a definition), it is automatically converted to a pointer to its first element. So, in s="Hello World";, the array created by "Hello World" is automatically converted to a pointer to the “H” that has been stored for the string literal. Then s="Hello World"; changes s to this pointer.

To copy the string into the memory pointed to by s, you can use strcpy(s, "Hello World");, or you can write your own code to copy the bytes one-by-one from the string literal into the memory pointed to by s.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
0

You try to copy your string like a character, but you can't in C. You should use the function strcpy;

#include <string.h>

int main(void)
{
    char *s = malloc(15);

    strcpy(s, "Hello World");
    free(s);
    return 0;
}

Moreover you can use the function strdup to duplicate a string like that:

#include <string.h>

int main(void)
{
    char *s = strdup("Hello World");

    free(s);
    return 0;
}

The function strdup allocate memory and copy byte per byte the source in the destination, then return the destination.

M.M
  • 138,810
  • 21
  • 208
  • 365