Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leak question in C after moving pointer (What exactly is deallocated?)

I realize the code sample below is something you should never do. My question is just one of interest. If you allocate a block of memory, and then move the pointer (a no-no), when you deallocate the memory, what is the size of the block that is deallocated, and where is it in memory? Here's the contrived code snippet:

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

int main(void) {
    char* s = malloc(1024);
    strcpy(s, "Some string");
    // Advance the pointer...
    s += 5;
    // Prints "string"
    printf("%s\n", s);
    /*
     * What exactly are the beginning and end points of the memory 
     * block now being deallocated?
     */
    free(s);
    return 0;
}

Here is what I think I happens. The memory block being deallocated begins with the byte that holds the letter "s" in "string". The 5 bytes that held "Some " are now lost.

What I'm wondering is: Are the 5 bytes whose location in memory immediately follows the end of the original 1024 bytes deallocated as well, or are they just left alone?

Anyone know for sure what is it the compiler does? Is it undefined?

Thanks.

like image 652
Mario Avatar asked Aug 12 '09 15:08

Mario


1 Answers

You cannot pass a pointer that was not obtained from a malloc, calloc or realloc to free (except NULL).

Question 7.19 in the C FAQ is relevant to your question.

The consequences of invoking undefined behavior are explained here.

like image 81
Sinan Ünür Avatar answered Nov 11 '22 14:11

Sinan Ünür