I write this program for print content of a string in c language.
but dont print string!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define GROW_BY 10
int main(){
char *ptr_s;
int c;
ptr_s= (char *) malloc(GROW_BY);
printf("please enter a stringn");
while((c=getchar() ) !='n'){
*ptr_s++=c;
}
*ptr_s=0;
printf("the string is : n %s n", ptr_s);
}
result is :
the string is:
do not print content of string in ptr_s.
where is problem?
1
-
The original address stored in
ptr_s
is needed to print the string but it is lost when you advance the pointer. You also want that tofree()
the memory you allocated (OS will do it for you, but if youfree()
memory tools like valgrind will be able to tell about leaks you don’t know about). -
Code is subject to a buffer overflow as you don’t limit the string to at most
GROW_BY-1
. -
Don’t cast the void pointer from
malloc()
. It’s not needed and may hide problems. -
Consider using (POSIX)
getline()
.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define GROW_BY 10
int main(){
char *ptr_s = malloc(GROW_BY);
printf("please enter a string: ");
size_t i = 0;
for(; i + 1 < GROW_BY; i++) {
int c = getchar();
if(c == 'n') break;
ptr_s[i] = c;
}
ptr_s[i]='';
printf("the string is: "%s"n", ptr_s);
free(ptr_s);
}
and example run:
please enter a string: hello world
the string is: "hello wor"
2
the problem is use of original value of ptr_s in increment
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define GROW_BY 10
int main(){
char *ptr_s, *copy_ptrs;
int c;
ptr_s= (char *) malloc(GROW_BY);
copy_ptrs=ptr_s;
printf("please enter a stringn");
while((c=getchar() ) !='n'){
*copy_ptrs++=c;
}
*copy_ptrs=0;
printf("the string is : n %s n", ptr_s);
}