-1
for (int a=0; a<10; ++a) {
    printf ("%d", a);
}

char *foo;
foo = (char*)malloc(a); 

I want to store more than one char value in foo variable.

Should I change it to an array, since the buffer is only allocating 1 char length?
Is 1 the longest length that can be stored in this buffer?

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256

3 Answers3

2

Well, foo now points to some useable address of a bytes, because this is how malloc() works. It doesn't matter if its type is char *, void * or anything else, you can only use a bytes.

Here, you increment a to 10. That means you can store 10 bytes, being 10 chars, (because in the context of C, 1 char = 1 byte), starting at the address where foo points to. Using a pointer or an array is strictly equivalent.

Magix
  • 4,989
  • 7
  • 26
  • 50
1

Since the buffer is only allocating 1 char length...

No, it is not the case here.

Quoting from the C11 standard, chapter §7.22.3.4, The malloc function

void *malloc(size_t size);

The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate.

So, in case of

foo = malloc(a); //yes, the cast is not required

a memory of size same as the value of a will be allocated, considering malloc() is successful.

Simply put, if I write a snippet like

 int * p = malloc(10 * sizeof*p);

then, I can also write

 for (int i = 0; i < 10, i++)
     p[i] = i;

because, I have allocated the required memory for 10 ints.

That said, please see this discussion on why not to cast the return value of malloc() and family in C..

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

There are a couple of things you could do in a case like this.

  1. If you know at compile time how many chars you want to store you could make it an array char foo[10]; If you know that there is always going to be 10 (or less) characters you want to store.
  2. If you are not sure how many chars it needs to hold at compile time you would typically do dynamic allocation of memory using malloc. Now when using malloc you specify how many bytes of memory you want so for 12 chars you would do malloc(12) or malloc(12 * sizeof(char)). When using malloc you need to manually free the memory when you are done using it so the benefit of being able to ask for arbitrary (within limits) sizes of memory comes at the cost of making memory management harder.

As a side note: You typically do not want to cast the return value of malloc since it can hide some types of bugs and void *, that malloc returns can be implicitly cast to any pointer type anyway.

evading
  • 3,032
  • 6
  • 37
  • 57