简体   繁体   中英

memory allocation for char pointer

I am actually supposed to dynamically store a string . I have tried the below, It is printing everything but it terminating as soon as a space is included in my input. can someone explain is why?

Also what is the right way to do it :

int i;
char *a;
a=(char *)malloc(sizeof(char));
scanf("%s",a);
for(i=0;*(arr+i)!='\0';i++)
   printf("%c",*(arr+i));

It is printing everything but it terminating ...

Consider your memory allocation statements:

char *a;
a=(char *)malloc(sizeof(char));

By allocating only sizeof(char) bytes to the buffer a , then attempting to write anything more than the null terminator to it, you are invoking undefined behavior . (Note: sizeof(char) in C is by definition equal to 1 , always)

C strings are defined as a null terminated character array . You have allocated only one byte. The only legal C string possible is one containing only the null termination byte. But your code attempts to write much more, and in so doing encroaches on memory locations not owned by your process. So in general, when creating strings, follow two simple rules:

  • Determine max length of string you need
  • allocate memory to max length + 1 bytes to accommodate termination byte.

Example if max string is x characters long, create the memory for x + 1 characters:

char inputStr[] = {"This string is x char long"};
char string = malloc(strlen(inputStr) +1); //+1 for null byte
strcpy(string, inputStr);

Note, in C it is not recommended to cast the return of malloc() and family.

You've two problems with your code. Firstly, you only allocate enough space for 1 character and since strings have to be NUL terminated, the longest string you could have is 0 characters long. Since you don't know how long the text you're going to read in, you could start with an arbitrary size (say 1024).

a=malloc(1024);

Secondly, scanf will only read up to the next space when you use "%s". It also isn't constrained by the available space in a . A better way to to read in an entire line of text, is to use fgets like this

fgets(a,1024,stdin);

This will read up to 1023 characters or up to and including the next newline character. It will NUL terminate the string for you as well.

You can then print it as a string.

printf("%s",a);
char *a;

/* Initial memory allocation */
a = (char *) malloc(1024);      //  your buffer size is 1024

// do something with a

free(a);

Copy bellow string in your variable then print the string with "%s" as string and theres no need use of "%c" :

strcpy(a, "this is a string");
printf("String = %s", a);

Dont forget using of free() , if you dont use of this then you will get memory leak problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM