0

How should I store the pointers returned from malloc? I have a small parser that allows nested includes in the source files, meaning the first source file can include foo, then foo can include bar and so on.

This feature forces me to keep the memory allocated to each file intact, while opening new files -- therefore allocating new bunch of memory, and keep parsing them until the last file is opened and the last line is parsed, and then I can start freeing up the memory from the very last opened file.

The first thing came to my mind was to implementing a Stack to keep track of the allocated memory. As I'm doing this for the purpose of learning C, I started reading up how can I store returned pointers from malloc, however there is so much noise around similar topics like "how to cast malloc" that I couldn't find anything helpful.

Then I checked the malloc documentation and it says that malloc returns void pointers, but as far as I know it is generally not recommended to use void pointers as you can't dereference void pointers.

I don't think I need to dereference malloc pointers, since I will only need to pass them to the free and I shall be fine, however I was wondering if there are any well-known solutions regarding properly storing these pointers in my stack?

The goal is simply to keep track of the allocated memory via stack, so at any moment the pointer to the most recent allocated memory can be poped-out and freed when needed.

2 Answers 2

2

When you use malloc, you are asking for a chunk of memory in which you intend to store something. The malloc function is general-purpose, and neither knows nor cares what type of object you intend to store in the memory it has given you. The pointer-to-void (void*) return type is the manifestation of malloc's general purpose nature. If, for example, the memory is to contain a big long string of characters, you might choose to accept the pointer into a variable of type char*. Strong typing forces you to explicitly cast the void* to char*. If you want to create a stack of pointers, then - to continue the example - you would have a stack of char* items. The free function takes a pointer to void (void*), but casting rules say that a pointer to anything can be implicitly cast to a pointer to void, so you can simply pass your char* pointer to free and it's all good.

Bottom line - as far as malloc is concerned, there is no right or wrong way to store pointers it has returned... it all depends on what you intend to do with the memory; the design of your solution will dictate the optimum approach for handling the pointers.

7
  • No, casting (void *) to any other type does actually not gain any more type-safety. It actually defys that, as it shadows a change in the return type (which is - granted - unlikely for malloc(), but for other functions it might be very well). The standard explicitly allows assigning void * without typecast (and back). This is actually the only operation allowed for void *. Ok, in the second part you got it right May 9, 2015 at 21:29
  • I was just trying to keep my answer focused on the point of the question. Agreed, casting can get you into trouble, but when you are using malloc, what else are you going to do? At least C++ has new to give you allocations in a requested type, but that's a whole other matter.
    – Zenilogix
    May 9, 2015 at 21:34
  • @Zenilogix Thanks for the answer. I have char *, so I can simply have an array of chars and store the pointers, right? and since void is the widest available pointer it won't be damaged when I'm passing char * to the free. Did I understand it correctly?
    – Mahdi
    May 9, 2015 at 21:41
  • You need char *, not char! And its void *; void by itself is not a valid datatype for variables. Think of it as "Nothing" (which is different from NULL which basically means "invalid"). And yes, void * is compatible with other normal pointers. Sidenote ther might be special other pointers for e.g. embedded systems which might have different properties. May 9, 2015 at 21:44
  • @Mahdi: sorry for being picky, but that helps very much in this field. May 9, 2015 at 21:51
1

You shall not dereference void * or use them in expressions with casts. But you can store them as other pointers. However, I suspect you already have assigned them to something like MyType *myptr = malloc(...), so why not store them as MyType *? However, if you have a parser and really don't need the memory anymore (that's actually what you wrote), why would you want to keep the memory after all? It would be more efficient to free it once asap. And you do not need an extra structure for them.

If you have problems as the blocks are different types, you might have a look at anonymous structs/unions (since C99), which allow some basic class-derivation, so you can store the objects and process them later without casting. If using gcc, you might also find -fplan9-extensions quite appealing (I love those!). This will greatly increase type-safety if used properly. But be aware that you will leave the ISO-path then! (However, use the force).

7
  • Thanks for the answer. I actually need to keep the memory. Imagine I first open the first file, then in the middle of parsing I have to open another file. Here I can't free up the memory that is allocated to the first file, right? Otherwise I won't be able to continue parsing it after finished the included file.
    – Mahdi
    May 9, 2015 at 21:39
  • 1
    Ok, so you do have to access the data when stored. Yes, for this a stack would be ok, but you really should store the proper type, Normally it is no good idea to keep void * stored somewhere. You should only use it as function arguments/(result) under very well controlled conditions (avoid it whenever possible), but store well-typed pointers. Oh, regarding char remember these can be signed or unsigned! This is ok, if you dont use arithmetic operations on them which may yield a negative result. May 9, 2015 at 21:50
  • Great, so do you recommend unsigned char -- given the fact that I'm not gonna do any pointer arithmetic or char is enough?
    – Mahdi
    May 9, 2015 at 21:55
  • You should use that type which suits your needs best. If you just have char, that is ok. However, from you question, I would expect you want at least store the text and the index of the current position. This calls for a struct (this might be a good idea anyways, as it can easily be expanded). Remember that C allows to have a flexible array member as the last member. So there is actually no overhead for an extra pointer (and malloc). May 9, 2015 at 23:04
  • I did not talk about pointer arithmetic. Remember char is not a pointer type anyway. No offense, but you might get more comfortable with the notation and semantics if you have problems taking these things apart from each other. (honestly: no offense!) May 9, 2015 at 23:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.