You are trying to free something that is not a pointer to a "free" memory address. Just because something is an address does not mean that you need or should release it.
There are two main types of memory that you seem to be confusing: the memory stack and heap memory.
Stack memory lives in real time function. This is a temporary space for things that should not grow too big. When you call the main function, it allocates some memory for your variables that you declared ( p , token , etc.).
Memory βA heap lives when you malloc it, when you are free . You can use a lot more heap memory than you can add memory. You also need to keep track of it - it's not as easy as a stack memory!
You have a few errors:
You are trying to free memory, not a bunch of memory. Do not do this.
You are trying to free the inside of a memory block. When you actually allocated a block of memory, you can only release it from the pointer returned by malloc . That is, only from the beginning of the block . You cannot free part of the block from the inside.
For your code here, you probably want to find a way to copy the corresponding piece of memory to another location ... say, another block of memory that you put aside. Or you can change the original string if you want (hint: char value 0 is a null terminator and tells functions like printf to stop reading the string).
EDIT: The malloc function allocates heap memory *.
"9.9.1 malloc and free functions
The C standard library provides an explicit allocator known as the malloc package. Programs allocate blocks from the heap by calling the malloc function. "
~ Computer Systems: A Programmer's Perspective, Second Edition, Bryant and O'Hallaron, 2011
EDIT 2: * Standard C does not actually indicate anything about a heap or stack. However, for those who study on the appropriate desktop / laptop computer, the distinction is probably unnecessary and confusing if anything, especially if you learn about how your program is stored and executed. When you find yourself working on something like an AVR microcontroller, as is the case with H2CO3, itβs worth noting all the differences that, from my own experience with embedded systems, greatly expand the memory allocation.
GraphicsMuncher
source share