c program doesn't give me errors - c

Consider the following program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct my_string{
int len;
char *buf;
} my_string_t;
my_string_t *init_my_string(char *);
my_string_t *call_init_my_string();
int main(int argc, char *argv[])
{
my_string_t *st1 = call_init_my_string();
printf("%d\n", st1->len);
printf("%s\n", st1->buf);
free(st1);
return 0;
}
my_string_t *call_init_my_string()
{
my_string_t *st1 = init_my_string("Foo");
return st1;
}
my_string_t *init_my_string(char *s)
{
my_string_t *st = (my_string_t *) malloc(sizeof(*st));
st->len = strlen(s);
st->buf = s;
return st;
}
The question is,
does this program suppose to result in undefined behaviour or some kind of error?
since the string "Foo" inside function call_init_my_string is locally declared
and get passed to init_my_string function. In init_my_string function, I allocate
a space to hold the size of of the string and the string itself, but as i know, this
allocation
my_string_t *st = (my_string_t *) malloc(sizeof(*st)); only allocate enough space for st->len
and st->buf pointer and not for string "Foo" since I only assign the string
to st->buf instead of allocating it first and then do like the following:
st->buf = (char *) malloc(strlen(s) + 1);
memcpy(st->buf, s, strlen(s));
st->buf[strlen(s)] ='\0';
But after I compile it and run, it gives me no errors and the program runs fine.
why this program works fine and gives me no errors?
this is the result printed on the screen:
$ gcc struct_ptr_string1.c -o struct_ptr_string1
$ ./struct_ptr_string1
3
Foo

There's no undefined behaviour in your code.
The string literal "Foo" has static storage duration. You are passing its address to init_my_string and simply store that address (essentially a pointer to "Foo").
Your code is equivalent to (except we have one more copy of "Foo"):
my_string_t *call_init_my_string()
{
static char s[] = "Foo";
my_string_t *st1 = init_my_string(&s[0]);
return st1;
}
my_string_t *init_my_string(char *s)
{
my_string_t *st = malloc(sizeof(*st));
st->len = strlen(s);
st->buf = s;
return st;
}

The "Foo" string is a constant string probably stored somewhere statically. What happens in init_my_string is that you indeed allocate a new memory chunk, but you will assing st->buf to s which is the pointer which points to this "Foo" string. So you dont copy "Foo", but rather just set st->buf to the location where it is stored.
my_string_t *init_my_string(char *s)
{
my_string_t *st = (my_string_t *) malloc(sizeof(*st));
printf("st address=%d\n", st);
printf("s address=%d\n", s);
st->len = strlen(s);
st->buf = s;
printf("st->buf address=%d\n", st->buf);
return st;
}
Output:
st address=19779600
s address=4196344
st->buf address=4196344
3
Foo
As you see st->buf actually points to the constant string thats why no error.

Related

Change pointer of pointer in C

I'm trying to write a void function that gets a pointer to a pointer of a string (char**) as a parameter, and changes the original char* so it pointed to another string, lets say "hello".
Below is the code I've written:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void change_ptr(char **str_ptr)
{
char hello[] = "hello";
char *hello_ptr = hello;
*str_ptr = hello_ptr;
}
int main()
{
char str[] = "yay";
char *str_ptr = str;
char **ptr_to_str_ptr = &str_ptr;
change_ptr(ptr_to_str_ptr);
printf("%s\n", str);
return 0;
}
As you can see, Im getting the pointer to the pointer of the char* "yay", delivering it to the function, and in the function I'm getting the pointer to "hello", and changes *str_ptr (which is the pointer to the original string) to the pointer to hello. But when I print str at the end, it prints "yay".
What am I doing wrong?
(when I debug with printing the addresses, everything seems fine.)
This works:
#include <stdio.h>
void change_ptr(const char ** str_ptr)
{
*str_ptr = "hello";
}
int main()
{
char str[] = "yay";
const char * str_ptr = str;
const char ** ptr_to_str_ptr = &str_ptr;
change_ptr(ptr_to_str_ptr);
printf("%s\n", str_ptr);
}
Note that the string "hello" in this example is read-only because it is a string literal. I added const in a few places so you are reminded of this and the compiler will warn you if you try to write to the string. The pointer str_ptr can be modified, but not the string itself.

Segmentation fault when trying to copy string with double pointer

Jus started learning about pointers and im stuck with this program outputting a segmentation fault.
Its supposed to copy the first 10 Characters of a string to the location pointed by the double pointer
using gdb ive found that **pt=*s; produces the seg fault
#include <stdio.h>
#include <stdlib.h>
void str1(char *s, char **pt);
void str1(char *s, char **pt){
for(int i=0;i<10;i++){
**pt=*s;
pt++;
s++;
}
}
int main (void) {
char str[30] = "223This is test";
char *ptr;
str1(str, &ptr);
printf("%s", ptr);
return 0;
}
First of all ptr is not initialized, you can't really use it until you reserve space for it or store a valid memory address in it, i.e. make it point to some valid variable.
char *ptr = malloc(11);
Then you need to increment it properly in the function:
(*pt)++;
Once the copy is completed you need to null terminate the char array so it can be treatead as a string, aka a null terminated char array.
**pt = '\0';
Now as ptr was passed as a pointer to pointer, the increment is known by the caller, main in this case, so when you try to print it, it prints nothing because it's pointing to the end of the char array, we need to bring it back to the beggining.
*pt -= 10;
Corrected code with comments taking yours as base:
Live demo
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
void str1(char *s, char **pt) {
for (int i = 0; i < SIZE; i++) {
**pt = *s;
(*pt)++; //properly increment pt
s++;
}
**pt = '\0'; //null terminate copied string
//since ptr was passed as **, the increment is known by the caller
//now ptr will be pointing to the end of the string
//we have to bring it back to the beginning
*pt -= SIZE;
}
int main(void) {
char str[] = "223This is test";
char *ptr = malloc(SIZE + 1); //space for 10 character + null-terminator
//check for allocation errors
if(ptr == NULL){
perror("malloc");
return EXIT_FAILURE;
}
str1(str, &ptr);
printf("%s", ptr);
free(ptr);
return EXIT_SUCCESS;
}
You probably want this:
#include <stdio.h>
#include <stdlib.h>
void str1(char* s, char** pt) {
char *p = malloc(100); // allocate memory for destination
*pt = p; // store it for the caller
for (int i = 0; i < 10; i++) {
*p = *s;
p++;
s++;
}
*p = 0; // put string terminator, otherwise printf won't work correctly
}
int main(void) {
char str[30] = "223This is test";
char *ptr; // for now p points nowhere
str1(str, &ptr); // now p points to the memory allocated in str1
printf("%s", ptr);
free(ptr); // free memory for completeness
return 0;
}

Memory management in replace function

I'm trying to make a replace function in C. I know there are many out there that I could copy, but I decided to make my own function in order to practice.
However, I'm stuck at this:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void replace_content(char *rep, char *with, char **text) {
int len_rep = strlen(rep);
int len_with = strlen(with);
char *p = *text;
int new_text_size = 0;
char *new_text = malloc(new_text_size);
do {
if (!strncmp(p, rep, len_rep)) {
new_text_size += len_with;
new_text = (char *) realloc(new_text, new_text_size + 1);
strcat(new_text, with);
p += len_rep;
} else {
new_text_size++;
new_text = (char *) realloc(new_text, new_text_size);
new_text[new_text_size-1] = *p;
p++;
}
} while (*p != '\0');
*text = malloc(new_text_size);
strcpy(*text, new_text);
}
int main() {
printf("Testing a replace function:\n");
char *text =
"<serviceName>\n"
" <label1>a</label1>\n"
" <label2>b</label2>\n"
" <label3>c</label3>\n"
"</serviceName>\n";
printf("Before replace:\n%s", text);
replace_content("serviceName>", "serviceNameResponse>", &text);
printf("After replace:\n%s", text);
return 0;
}
This is the output I'm seeing so far:
Testing a replace function:
Before replace:
<serviceName>
<label1>a</label1>
<label2>b</label2>
<label3>c</label3>
</serviceName>
After replace:
<0�serviceNameRespons
<label1>a</label1>
<label2>b</label2>
<label3>c</label3>
</serviceNameResponse>
My guess is that I'm doing something wrong with dynamic memory, but the more I look into my code the more confused I am.
These two statements are problematic:
new_text = (char *) realloc(new_text, new_text_size + 1);
strcat(new_text, with);
The first problem is that you should never assign back directly to the pointer you reallocate. That is because realloc may fail and return NULL, making you lose the original pointer.
The second problem is that new_text doesn't initially point to a null-terminated string, which makes the call to strcat undefined behavior.
There is also a problem in the else branch:
new_text = (char *) realloc(new_text, new_text_size);
new_text[new_text_size-1] = *p;
Besides the same problem with reassigning back to the pointer being reallocated, you don't terminate the string in new_text.
May the reason is malloc(0) in line 10 char *new_text = malloc(new_text_size);.
The malloc() function allocates size bytes and returns a pointer to
the allocated memory. The memory is not initialized. If size is 0,
then malloc() returns either NULL, or a unique pointer value that
can later be successfully passed to free().
I suggest using char *new_text = NULL; instead.

I'm trying to understand function returning local pointer, char array vs char pointer

I'm getting output as "pqrs", But my understanding was we cannot return local pointer. I'm started to think since char *t = "pqrs" is string literal and it will be in read-only memory area, so we can return the local pointer — But not sure if my understanding is correct
#include <stdio.h>
#include <string.h>
char *t(char *s1)
{
char *t = "pqrs";
s1 = "fdsa";
return t;
}
int main()
{
char *s = "abcde";
s = t(s);
printf("%s \n",s);
return 0;
}

Allocating memory to a struct member pointer in C

I have a structure with a member that I need to pass to a function by reference. In that function, I'd like to allocate memory & assign a value. I'm having issues somewhere along the line - it seems that after the code returns from allocateMemory, the memory that I had allocated & the values that I assigned go out of scope (this may not be exactly what is happening, but it appears to be the case).
#include <stdio.h>
#include <stdlib.h>
typedef struct myStruct_t
{
char *myString;
} myStruct;
void allocateMemory(void *str);
int main(void) {
myStruct tmp = {
.myString = NULL
};
myStruct *p = &tmp;
allocateMemory(p->myString);
//allocateMemory(&(p->myString)); //also tried this
printf("%s", p->myString);
return 0;
}
void allocateMemory(void *str)
{
str = malloc(8);
((char *)str)[0] = 'a';
((char *)str)[1] = 0;
}
If I print the value of str inside of allocateMemory, the 'a' is successfully printed, but if I attempt to print p->myString in main, my string is empty.
Can anyone tell me what I'm doing wrong?
You need to pass address of the structure member and then you can change (aka allocate memory) to it. In your version of the function, you are not taking a pointer not reference of a pointer, so you can change the content of memory referenced by the pointer but not the pointer itself.
So change your function to
void allocateMemory(char **ret_str)
{
char *str = malloc(8);
str[0] = 'a';
str[1] = 0;
*ret_str = str;
}
And then call it as
allocateMemory(&p->myString)
An alternative way of writing the same function Rohan did, eliminating the need to define any new variables:
void allocateMemory(char **str, size_t size) {
*str = malloc(size);
(*str)[0] = 'a';
(*str)[1] = '\0';
}
Note that I pass a size parameter to justify using malloc() in the first place.

Resources