Noktua Noktua - 11 days ago 8
C Question

Warning: assignment from incompatible pointer type at malloc?

I watched the other two questions about this problem, but I think they are different. Thanks for your help. Problem is in the 18th line.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

typedef struct x {
char name1[30];
char name2[30];
} x;

int main() {
int *ptr;
x array[2] = {
{ "Apple", "Battle" },
{ "Cup", "Dog" },
};
ptr = (x*)malloc(sizeof(x)); /*assignment from incompatible pointer type*/
printf("write something");
scanf("%s", array[3].name1);

free(ptr);

return 0;
}

Answer

Multiple problems in your code:

  • You cast the return value of malloc() as (x*) but store it to a pointer to int instead of a pointer to x. Why do you do this? If properly configured for useful warnings, the compiler will diagnose a potential error here.

  • scanf("%s", array[3].name1); stores a word into the name1 member of a member of array that has not been defined. The size of the array is 2, the only valid index values as 0 and 1. This code invokes undefined behavior.

  • The %s scanf format would also cause a potential buffer overflow since scanf can try an store more that 29 characters plus a null terminator into the member. You should use %29s.

  • What is the purpose of your function?