Memory Merge Error

I have a small piece of code. I compiled it with help -lmcheckas I try to debug code where I have the same error.

I get this error when running this code:

memory clobbered before allocated block

Can someone explain the reason why free(ptr)this error will be thrown to me?

How else can I free the pointer?

Thank.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define LEN 5


int main(int argc, char *argv[]){

    char *ptr = NULL;

    ptr = (char *) malloc(LEN+1);// +1 for string
    strcpy(ptr, "hello");

    int i = 0;
    for(i = 0; i<LEN; i++)
    {
        printf("ptr[%d] = %c\n", i, ptr[i]);
        ptr++;
    }
    free(ptr);


    return 0;
}
+5
source share
4 answers

You increase ptr, therefore, change the address to which it points. You cannot do this.

In your case, specify a separate pointer, say char * p = ptrand perform your operations with p, leaving ptrintact so that you can free(ptr)later.

EDIT , , ptr++, . ptr[i], ptr, ptr[i] ( ) .

(ptr++), . , :

int main(int argc, char *argv[]){

    char *ptr = NULL;
    char * p; 

    ptr = (char *) malloc(LEN+1);// +1 for string (please check for NULL)
    p = ptr;

    strcpy(ptr, "hello");

    int i = 0;
    while (*p) // note how I changed it to a while loop, C strings are NULL terminated, so this will break once we get to the end of the string. What we gain is that this will work for ANY string size.
    {
        printf("ptr[%d] = %c\n", i++, *p); // here i dereference the pointer, accessing its individual char
        p++;
    }
    free(ptr);


    return 0;
}
+8

ptr .

+2

, , ptr, ptr[i] , ; "hlo".

+1

Find the answer in the comments. When you allocate some memory, as a rule, the memory management structure monitors it, adding additional information (you can say “Header and footer”) to the allocated memory area. When you free this memory, the same information is matched to detect any unwanted / invalid memory access.

int main(int argc, char *argv[]){

    char *ptr = NULL;
    char* temp = NULL;           // Have a temp pointer.

    ptr = (char *) malloc(LEN+1);// +1 for string
    strcpy(ptr, "hello");

    temp = ptr;                 // manipulate temp pointer instead of ptr itself

    int i = 0;
    for(i = 0; i<LEN; i++)
    {
        printf("ptr[%d] = %c\n", i, temp[i]);
        temp++;                 // Why you are incrementing this? Just to print, there is no need of this.
    }
    free(ptr);


    return 0;
}
+1
source

All Articles