C language malloc to allocate memory pointer to a structure member

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_25908839/article/details/102733282

Problem: When members of a structure of a pointer type, when the memory for the structure of the application, does not give the members to allocate memory pointer.

Procedures are as follows:

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

typedef struct example
{
	int *a;
	char *b;
}example_t;

int main(int argc, char** argv)
{
	example_t *exam;
	exam = (example_t *)malloc(sizeof(example_t));
	if(NULL == exam)
	{
		printf("%s\n", "exam malloc failed");
		return -1;
	}
	printf("%p\n", exam);
	printf("%p\n", exam->a);
	printf("%p\n", exam->b);
	free(exam);
	return 0;
}

The results are as follows:

$ gcc exam.c
$ ./a.out 
0x1051150
(nil)
(nil)

When the pointer members can be seen the structure is not allocated memory.

Solution: When the body structure of the application space, while giving pointers membership application space

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

typedef struct example
{
	int *a;
	char *b;
}example_t;

int main(int argc, char** argv)
{
	example_t *exam;
	exam = (example_t *)malloc(sizeof(example_t));
	if(NULL == exam)
	{
		printf("%s\n", "exam malloc failed");
		return -1;
	}
	printf("%p\n", exam);
	printf("%p\n", exam->a);
	printf("%p\n", exam->b);

	printf("\n");

	exam->a = (int *)malloc(sizeof(int));
	exam->b = (char *)malloc(sizeof(char));

	printf("%p\n", exam);
	printf("%p\n", exam->a);
	printf("%p\n", exam->b);

	free(exam);
	free(exam->a);
	free(exam->b);
	return 0;
}

The results are as follows:

$ gcc exam.c 
$ ./a.out 
0xd8d150
(nil)
(nil)

0xd8d150
0xd8d568
0xd8d578

In this case, the structure pointer member has allocated memory.

 

Guess you like

Origin blog.csdn.net/qq_25908839/article/details/102733282