How to allocate memory to struct pointer using malloc.h header? - c

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct student
{
char name[25];
int age;
};
int main()
{
struct student *c;
*c =(struct student)malloc(sizeof(struct student));
return 0;
}
What is the wrong with this code? I tried times by alternating this code to allocate memory to struct pointer. But this error comes when compiling:
testp.c:15:43: error: conversion to non-scalar type requested
*c =(struct student)malloc(sizeof(struct student));
^
I'm using mingw32 gcc compiler.

What is the wrong with this code?
Ans: First of all you change that "is" to "are", there are two major problems, atleast. Let me elaborate.
Point 1. You allocate memory to the pointer, not to the value of pointer. FWIW, using *c (i.e., de-referencing the pointer without memory allocation) is invalid and will result in undefined behaviour.
Point 2. Please do not cast the return value of malloc() and family in C. The cast you used is absolutely wrong and proves the authenticity of the first sentence.
To solve the issues, change
*c =(struct student)malloc(sizeof(struct student));
to
c = malloc(sizeof(struct student));
or, for better,
c = malloc(sizeof*c); //yes, this is not a multiplication
//and sizeof is not a function, it's an operator
Also, please note, to make use of malloc() and family , you don't need the malloc.h header file. These functions are prototyped in stdlib.h.
EDIT:
Suggestions:
Check for success of malloc() before using the returned pointer.
Always free() the memory once the usage is over.
The recommended signature of main() is int main(void).

This worked (on C and C++).
Since you originally included both tags.
change
*c =(struct student)malloc(sizeof(struct student));
to
c =(struct student*) malloc(sizeof(struct student));

Related

Which memory is being dereferenced by a struct pointer?

So I'm trying to understand how pointers work, especially with structs.
Here's the code I'm trying to understand
struct Node {
int val;
};
int main() {
Node* a = (Node*) malloc (sizeof(Node));
printf("%p\n", a);
printf("%p\n", &(a->val));
printf("%p\n", *a);
}
From my understanding if I print a, it would print the memory address of what was reserved by malloc. But I couldn't figure out which memory was being printed if I dereferenced a.
Here's the output.
00000000001C5D40
00000000001C5D40
00000000001C0150
I expected *a to be dereferencing the address of the first attribute. But as the output shows, it's not. So which memory is being dereferenced?
*a is the struct Node that a is pointing to. printf("%p\n", *a); passes the entire value of the struct Node. The “value” of a structure is an aggregate value composed of the values of all its members. In this case, there is just one member. And, since you did not assign any values to the member, its value is indeterminate.
However, for %p, you are intended to pass a pointer to printf (specifically a pointer of type void *). When you do not, the C standard does not define the behavior. The argument-passing mechanism may go awry in various ways. It might format the value in the member val as if it were a pointer and print that. Or it might print some unrelated data that happened to be a register where printf expected to find the pointer it should have been passed. Or your program could crash.
When you dereference a pointer to struct Node (*a) you get the struct Node variable itself. If you had not initialized it you can get whatever (garbage). So in your case (00000000001C0150) is some garbage that was at the moment in variable struct Node.
So I added one line in your code for clarity:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int val;
};
int main() {
struct Node* a = (struct Node*) malloc (sizeof(struct Node));
a->val = 1;
printf("%p\n", a);
printf("%p\n", &(a->val));
printf("%p\n", *a);
}
And I got the following result:
0xaaab04e522a0
0xaaab04e522a0
0x1
Hope, I help you a little bit)

Structures and dynamic memory in C

I'm a beginner in C.
I want to assign each person's info to an array of pointer that is *arr[2]
but I get an error message that is
'malloc' is not declared in this scope.
How can I fix it?
#include <stdio.h>
int main()
{
struct person {
char *name;
int number;
char gender;
};
struct person *arr[2];
arr[0] = (struct person *) malloc(sizeof(struct person));
arr[0]->name = "john";
arr[0]->number = 123;
arr[0]->gender ='m';
arr[1] = (struct person *) malloc(sizeof(struct person));
arr[1]->name = "jessica";
arr[1]->number = 456;
arr[1]->gender ='w';
printf("%s", arr[1]->name);
return 0;
}
A few inputs than just one.
Primarily:
The man page for malloc says that you need to include the header file: stdlib.h
#include <stdlib.h>
The one habit which would save you a lot of pain going ahead is to check if malloc() was successful or not. You must check the value returned by malloc().
arr[0] = malloc(sizeof(struct person));
if(arr[0] == NULL)
{
// Since malloc has returned NULL, requested memory is not allocated
// Accessing it is out of question
// Some error handling implementation
return;
}
Additionally, we should always return what we borrow, unless we don't crash all of sudden. Allocated memory needs to be freed. There are several examples on internet on how to de-allocate the dynamically allocated memory. A good start would be reading concepts like Memory Leakage and Dangling pointers.
The other suggestion would be:
If you look at the same (or the other) man page for malloc, you'd find that malloc returns a void pointer. So, you do not have to cast the malloc() result. There is this legendary post and a legendary answer which explains why not to cast.
You should include a header which defines malloc(). Usually, this would be stdlib.h.
You can use online help from cppreference.com or similar sites to get this information, and full documentation for the c libraries.
To actually use the function malloc,you should include the #include library which declares among other things the malloc(), calloc(), free() functions.

pointers in C and use in linked list

I am struggling with understanding structs and pointers, and thus, struggling to understand examples of linked lists in both my textbook and online.
What does the following code mean:
(struct NODE *)malloc(sizeof(struct NODE));
Will someone please provide a detailed explanation?
I understand that something is being allocated memory (the size in bytes of struct NODE), however, I don't understand what
(struct NODE *)
means.
Function malloc() returns address of allocated memory. Return type of malloc() function is void* (it don't know for which type of data you are allocating memory), to assign it to pointer of your structure type you typecasts it into required type. So in you expression (struct NODE *) is typecast instruction:
(struct NODE *) malloc (sizeof(struct NODE));
^
| ^
Typecast | call of malloc function with argument = sizeof(struct NODE)
Generally, you should avoid typecast a returned value from malloc/calloc functions in C ( read this: Do I cast the result of malloc? )
In C syntax of typecast is:
(rhsdatatype) data;
rhsdatatype should be in parenthesis before data.
Sometime in programming you need typecast: for example.
int a = 2;
int b = 3;
double c = a / b;
This code outputs 0.0 because 2/3 both are integers to / result will be int that is 0, and you assigns to double variable c = 0. (what you may not wants).
So here typecast is solution, new code is:
int a = 2;
int b = 3;
double c = (double)a / (double)b;
it outputs real number output that is: 0.666.
malloc returns void*. (struct NODE *) is a cast of this to a pointer to NODE.
This cast is not required in C. Use of it is often considered poor style since it can cause bugs if you forget to include <stdlib.h> for a declaration of malloc.

Malloc syntax in C

In the books I read that the syntax for malloc is malloc(sizeof(int)) but in one of doubly linked list program I see the following:
newnode=(struct node *)malloc(sizeof(struct node))
What is (struct node*) doing here? What is this entire code doing? btw, the code for the struct in the program is as below.
struct node
{
char line[80];
struct node *next,*prev;
};
struct node *start=NULL,*temp,*temp1,*temp2,*newnode;
Thank you
The code is dynamically creating a pointer to a single type of struct node. In most versions of C, the (struct node *) cast is not needed, and some argue that it shouldn't be used. If you remove the cast, it will be a void*, which can be used for any type.
Therefore:
newnode = (struct node*)malloc(sizeof(struct node));
is roughly equivalent to:
newnode = malloc(sizeof(struct node));
See: Specifically, what's dangerous about casting the result of malloc?
Note 1: If you are using Visual Studio to write your C code, it will give you red underlining if you don't cast the result of malloc. However, the code will still compile.
Note 2: Using malloc in C++ code requires you to cast the result as shown in your example.
You ran into a very bad code. C programmers never cast a result of malloc(). Not only it is not needed but can be harmful.
You should pass the number of bytes that you want malloc to allocate as argument. That is why in this code sample you use sizeof(struct node) telling C to allocate the number of bytes needed for a struct node variable. Casting the result like is shown in this code is bad idea by the way.
malloc returns a void pointer .
(struct node*) does a explicit conversion from void pointer to the target pointer type
"malloc" returns a void-pointer. (struct node *) is type-casting the result of malloc to a "node struct pointer", which is (undoubtibly) what "newnode" is.

Struct memory allocation fault

I am writing a C project with pointers and structs, and right now facing this problem:
There is a structure
struct Customer
{
char Name[80];
char Address[40];
int ID;
int Pnumber;
};
and I am gonna make a dynamic array of this structs with *line_count* number of members. I use this code, but it crashes a program:
struct Customer* ph;
ph = (struct Customer*)malloc(line_count * sizeof(struct Customer));
What am I doing wrong?
Good:
struct Customer* ph;
ph = (struct Customer*)malloc(line_count * sizeof(struct Customer));
Better:
struct Customer* ph =
(struct Customer*)malloc(line_count * sizeof(struct Customer));
if (!ph) {
<<error handling>>
...
But frankly, it sounds like the problem is elsewhere in your code.
There's nothing fundamentally wrong with your malloc().
Maybe "line_count" is bogus, maybe "malloc()" is failing (in which case, it should return "NULL") ... or maybe you're accessing the struct incorrectly and/or failing to initialize it correctly.
A stack traceback of the actual crash would be very useful.
The piece of code you are showing might crash only if ph == NULL after the malloc call and you dereference it.
From the malloc man page:
The malloc() and calloc() functions return a pointer to the allocated
memory that is suitably aligned for any kind of variable. On error,
these functions return NULL. NULL may also be returned by a
successful call to malloc() with a size of zero, or by a successful
call to calloc() with nmemb or size equal to zero.

Resources