Doubt related dynamic memory allocation

Please tell me the difference between following codes: -
Because both time I got Same OUTPUT i.e "How are you".
then What is the use of malloc function?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

1.

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<string.h>
void main()
{
char *nm;
strcpy(nm,"How are you?");
printf("%s",nm);
getch();
}

2. 
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<string.h>
void main()
{
char *nm;
nm=(char*)malloc(200*sizeof(char));
strcpy(nm,"How are you?");
printf("%c",nm[i]);
free(nm);
getch();
}
Last edited on
Line 10: nm is an uninitialized pointer. No telling what it points to.
Line 11: You're copying "How are you?" to an uninitialized pointer. You're wiping out memory somewhere.

Line 24: malloc returns an array of 200 characters setting nm to a valid location on the heap.



While we're here,

void main() is just plain wrong. main returns an int.

Other parts of your code suggest you're learning C++ in the year 1995, using 16 bit DOS. I recommend you learn C++ in the year 2017 instead.
Last edited on
Topic archived. No new replies allowed.