PDA

View Full Version : Incompatible pointer type



slushpuppy
December 14th, 2008, 08:37 AM
#include <stdio.h>
#include <stdlib.h>


int main (int argc, char *argv[]) {
char **pointer,*p;
int i = 0;
pointer = malloc(9);
while (i <= 8) {
pointer[i] = malloc(31);
pointer[i] = "hello";
i++;
}
printf("%s\n",pointer[0]);
pointer = realloc(pointer,30);
while (i <= 19) {
pointer[i] = malloc(31);
pointer[i] = "hellllllooo";
i++;
}
}


The output message is a memory dump. I am compiling using gcc and the command $ gcc test.c. Thanks!

Bachstelze
December 14th, 2008, 08:54 AM
Replace


pointer = malloc(9);

with


pointer = malloc(9*sizeof(char*));

Or better yet:


pointer = calloc(9, sizeof(char*));

slushpuppy
December 14th, 2008, 09:08 AM
Replace


pointer = malloc(9);

with


pointer = malloc(9*sizeof(char*));

Or better yet:


pointer = calloc(9, sizeof(char*));

Hi, thanks. Could you kindly explain the significant of using the sizeof of a char pointer?

Bachstelze
December 14th, 2008, 09:15 AM
firas@nobue ~ % cat test.c
#include <stdio.h>

int main(void)
{
printf("%lu\n", sizeof(char*));
return 0;
}
firas@nobue ~ % cc -o test test.c
firas@nobue ~ % ./test
8


The size of a char* is thus 8 bytes. Therefore, if you do pointer = malloc(9), pointer will not be allocated enough memory to hold all the data you will put in it.

slushpuppy
December 14th, 2008, 09:57 AM
firas@nobue ~ % cat test.c
#include <stdio.h>

int main(void)
{
printf("%lu\n", sizeof(char*));
return 0;
}
firas@nobue ~ % cc -o test test.c
firas@nobue ~ % ./test
8


The size of a char* is thus 8 bytes. Therefore, if you do pointer = malloc(9), pointer will not be allocated enough memory to hold all the data you will put in it.
Thanks!