Invalid pointer error on invoking free() after malloc in C

Invalid pointer error on invoking free() after malloc in C

You have a variable p that points to the memory returned by malloc. Then you change the variable p to point to the memory occupied by the string literal mark. When you try to delete it, you are trying to delete the string literal.

In short, the line p = mark is not doing what you think its doing. It isnt copying that value into the memory returned from malloc.

Try changing that line to strcpy(p, mark) and I suspect things will start working better.

(That being said, I shouldnt even mention strcpy because its so unsafe and there are alternatives that will prevent buffer overrun problems. But thats a separate question, and there are a lot of discussions about it here on SO.)

The problem is that p does not point to memory allocated using malloc(). Instead, it contains a pointer into constant mark, so basically you are trying to delete a literal which is not allowed

int main() {
        int num = 0;
        //printf(Enter a number: );
        //scanf(%d, &num);
        char* p = (char*)malloc(16*sizeof(char));
        printf(%p, p);
        if(p) {
                strcpy(p,mark);
                printf(n%sn, p);
                free(p); //when removed no error
        }
        return 0;
}

usage of strcpy will solve the problem

Invalid pointer error on invoking free() after malloc in C

There is an error in your code:

 p = mark;

is wrong, p is a pointer i.e. it is suppose to contain an address value. you cannot assign to it a string. You must use the functions provided by the standard library such as strcpy or strncpy (header: string.h).

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

int main() {
        int num = 0;
        //printf(Enter a number: );
        //scanf(%d, &num);
        char* p = (char*)malloc(16*sizeof(char));
        printf(%p, p);
        if(p) {
                //*p = stmark;
                strcpy(p, mark);
                printf(n%sn, p);
                free(p); //when removed no error
        }
        return 0;
}

Leave a Reply

Your email address will not be published.