In my program I am trying to resize array using malloc function.
#include <stdio.h>
int main(void)
{
int list[5],i;
int* ptr = &list;
for(i = 0; i < 5; i++)
list[i] = i;
for(i = 0; i < 5; i++)
printf("%d\n", list[i]);
printf("----------------------------------------\n");
ptr = malloc(10);
for(i = 0; i < 10; i++)
list[i] = i;
for(i = 0; i < 10; i++)
printf("%d\n", list[i]);
}
While compiling the program I get two warnings :
searock@searock-desktop:~/C$ cc malloc.c -o malloc
malloc.c: In function ‘main’:
malloc.c:6: warning: initialization from incompatible pointer type
malloc.c:16: warning: incompatible implicit declaration of built-in function ‘malloc’
My program is running fine. I can't understand why the compiler is giving me this errors?
Should I change my approach?
Edit 1 : And then how do I free the memory? should I use free(list); or free(ptr);
Edit 2 : Updated Code
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int list[5],i;
int* ptr = malloc(5 * sizeof(int)); //&list;
for(i = 0; i < 5; i++)
ptr[i] = i;
for(i = 0; i < 5; i++)
printf("%d\n", ptr[i]);
printf("----------------------------------------\n");
ptr = realloc(ptr, 10 * sizeof(int)); //malloc(10);
for(i = 0; i < 10; i++)
ptr[i] = i;
for(i = 0; i < 10; i++)
printf("%d\n", ptr[i]);
free(ptr);
}
Thanks.
You aren't actually reallocating list. list is still 5 bytes, while ptr points to the 10 byte array.
Do something like this instead:
int* list = malloc(5 * sizeof(int));
...
list = realloc(list, 10 * sizeof(int));
...
Now, when you say:
int* ptr = &list;
You aren't creating a "reference" to list; in this context (not in general), it's the same as:
int* ptr = list;
This means ptr[3] and list[3] are the same int, but making ptr point to a new buffer won't make list point to a new buffer as well. If this were C++, the syntax for declaring ptr the way you're thinking would be (I think):
int (&ptr)[5] = list;
In any case, you can't realloc an automatically-allocated buffer, anyway. This won't work:
int buffer[5];
buffer = realloc(buffer, 10 * sizeof(int));
The realloc would likely cause a segmentation fault, and assigning the new pointer to buffer isn't allowed by C.
Finally, stealing from the other answers, you need to #include <stdlib.h> to use malloc and friends; otherwise, it'll be implicitly declared to return an int rather than a pointer, yielding warnings and screwing up 64-bit compatibility for no good reason.
Yes, malloc allocates 10 bytes, but 10 integers are 10 * (sizeof integer) bytes.
Use
malloc(10*sizeof(int));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With