1

I am puzzled by this response.Can anyone help me on this and point out where I am making a mistake? The output at codepad is "memory clobbered before allocated block"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char *s = (char *)malloc(10 * sizeof(char));
    s = "heel";
    printf("%s\n",s);
    printf("%c\n",s[2]);
    printf("%p\n",s);
    printf("%d\n",s);
    free(s);
    return 0;
}
James Raitsev
  • 92,517
  • 154
  • 335
  • 470
kevin
  • 173
  • 3
  • 10

4 Answers4

12

You're trying to free constant memory with:

free(s); // cannot free constant "heel"

What you're doing is allocating a piece of memory and storing its location (char *s). You are then overwriting that reference with one to a string constant "heel" (memory leak), which cannot be freed. To make this behave as desired, you should be copying the constant string to the memory you allocated:

strcpy(s, "heel");

Here is an example for getting user input:

char *input = malloc(sizeof(char) * 16); // enough space for 15 characters + '\0'
fgets(input, 16, stdin);

// do something with input

free(input);
  • Thanks Tim. So what it means is using malloc to initialize memory then and s = "heel" are 2 different things? Does s="heel" automatically initialize memory? – kevin Dec 26 '11 at 20:02
  • @kevin: When your program is started, the string constant "heel" is stored in memory and is read-only; `s = "heel"` assigns `s` to the location of that read-only string. So when you're trying to `free(s)` you'd get an error. –  Dec 26 '11 at 20:06
  • so what happens if I want to input a string from the keyboard and free the memory after I am done with it? – kevin Dec 26 '11 at 20:18
2

To expand on @TimCooper's answer:

  • first you do: char *s = (char *)malloc(10 * sizeof(char));
  • then: s = "heel";

The first line allocates memory and assigns the location of that memory to s. But the second line reassigns s to the memory location of constant string heel on the stack!

Which means you try and free() memory on the stack, which is illegal. AND you leak memory, since what you first allocated to s is now inaccessible.

If you want to write a string into the memory pointed by s, you should use something like strcpy() (or, better, strncpy()).

fge
  • 119,121
  • 33
  • 254
  • 329
1
char *s = (char *)malloc(10 * sizeof(char));
  s = "heel";

Doesn't do what you think, or what you would expect with more modern languages

The first line allocates some memory for 10chars and returns the address of it.

The second line changes that address to point to a constant block of memory allocated at compile time, containing "heel" losing the link to the allocated memory - leaking it

Martin Beckett
  • 94,801
  • 28
  • 188
  • 263
1

You cannot free(s) - it's constant memory.

Try to change s = "heel"; with strcpy(s,"heel");

SlavaNov
  • 2,447
  • 1
  • 18
  • 26