Variable passes out of scope and memory keeps values [duplicate] - c

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 years ago.
I am studying C programming and making some tests in Ubuntu with Geany. I have a question about pointers. When an array is declared in a function and then returned as a pointer, array values are lost in the main method. I could check this with a simple example:
#include <stdio.h>
char* msg ();
int main(int argc, char **argv)
{
char* p = msg();
int i;
for(i=0;i<=10;i++)
printf("i: %d, value: %c \n", i, p[i]);
return 0;
}
char* msg (){
char msg [] = "hello";
return msg;
}
The output is random values (excepting the first one that always is 'h'). I suppose that this is because the pointer passed out of the scope and the memory could be written by other functions.
But if the value of message is bigger enough (like thousands of characters for example or maybe less), values stand in the same memory place and I can read them despite of the array was created in other function.
What is the reason for this results?
Thank you so much.

Returning a pointer to an automatic local variable invokes undefined behavior.

Related

segmentation fault on calling a function for swapping some characters in a string [duplicate]

This question already has answers here:
Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer
(5 answers)
Closed 5 months ago.
#include <stdio.h>
void swapchars(int Q,char* L){
char *ptr;
for(int i=0;i<Q-1;i+=2){
*ptr= *(L+i);
*(L+i)= *(L+i+1);
*(L+i+1)= *ptr;
}
}
int main() {
// Write C code here
int N;
scanf("%d",&N);
char str[N+1];
scanf("%s",str);
swapchars(N,str);
printf("%s",str);
return 0;
}
I don’t know what is wrong with this code it keeps generating segfault although when I used the same loop directly in the main function without an external function the code was working properly
You haven't initialized ptr to anything, so dereferencing it is undefined - you are writing to a random place in memory.
Think about whether you really need a pointer to store the intermediate value.

Why printf prints same string when function called back to back inside same statement [duplicate]

This question already has answers here:
returning string from function without malloc
(8 answers)
Closed 6 months ago.
In the below snippet, printf( ) prints same string even though the char array has been memset to 0.
#include <stdio.h>
#include <string.h>
char ip_addr[20];
char *ip_print(char *in)
{
memset(ip_addr,0,20);
strcpy(ip_addr,in);
return ip_addr;
}
int main()
{
printf("Ip addresses %s - %s",ip_print("226.0.0.1"),ip_print("10.1.1.1"));
return 0;
}
output-
Ip addresses 226.0.0.1 - 226.0.0.1
Expected output-
Ip addresses 226.0.0.1 - 10.1.1.1
As #Pablo said above ip_print() updates a global variable and returns the (same) address twice. The order of evaluation of arguments, however, is unspecified so the result is undefined behavior (it may print either address twice).

Printing ���� when adding a string to an array of strings [duplicate]

This question already has answers here:
Since I can't return a local variable, what's the best way to return a string from a C or C++ function?
(8 answers)
Return a string from function to main
(3 answers)
How to access a local variable from a different function using pointers?
(10 answers)
Closed 3 years ago.
I kept getting the error "Command terminated by signal 11" when I try to save a string into an array of strings. After changing the code from the link below, now the name prints out ���W.
I used this link to fix my code off of but it is still causing me to get the error "Command terminated by signal 11".
#include<stdio.h>
#include<string.h>
void getName(char* c[], int size);
int main(void) {
int yenoSize = 0;
int strSize = 0;
char name1[30];
char* name[30];
char* students[5][30];
for(int i=0;i<1;i++){
getName(name, strSize);
students[i][0] = name1;
}
for(int k=0; k<1;k++){
printf("Student Name: %s \n", students[k][30]);
}
}
void getName(char* c[], int size){
char name1[30];
printf("Enter student name: ");
fgets(name1, 30, stdin);
c[0] = &name1[0];
printf("%s", name1);
}
The output is supposed to print out the name that the user inputs (Student Name: Jon) but it is currently printing ���W. How can I fix the problem? I believe the problem exists with the name pointer pointing to null. Is that the problem? I appreciate the help!
2 major issues.
1) In main(), you are calling getName() with name but storing name1 in students variable.
2) In function getName(), name1 is a local array. The scope of this variable is limited to getName(). You can not return address of name1 by assigning it to c[0] as it may get freed by OS after function returns. You can consider using malloc() for this.

Could not get the entered string from the stack of function [duplicate]

This question already has answers here:
Unable to modify pointer variable passed as argument to a function
(2 answers)
Closed 5 years ago.
#include <stdio.h>
#include <stdlib.h>
static void get_string(char *ac)
{
ac = (char *)malloc (1 * sizeof (char));
printf("Enter the string to count vowels and consonants in a string using pointers: ");
scanf("%s", ac);
}
main(int argc, char *argv[])
{
char *ac = NULL;
get_string(ac);
printf("The Entered string is:%s", ac);
for(;;);
}
Could not get the entered string from the stack of function. Returns null.Can anyone help me in debug?
Function arguments in C is passed by value. Any changes made to the parameters from inside the called function will not reflect to the actual argument supplied at function call.
In your case, you wanted to change ac itself (not the content of the memory location it points to), so, that would need a pointer-to-ac.
That said,
Please see this discussion on why not to cast the return value of malloc() and family in C..
sizeof(char) is guaranteed to be 1 in C, no need to use it as multiplier
a memory allocation of 1 byte can only hold an empty string, that's probably meaningless (and erroneous) in your code.

function returns address of local variable in c [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 years ago.
I make a function to add character to string and I have the next error message function returns address of local variable please help me, my code below.
int main(int argc, char** argv)
{
char* string;
string ="hola mundo";
char c ='x';
string = cadena_mas_caracter(string,c);
printf("texto sumado %s",string);
return (EXIT_SUCCESS);
}
char *cadena_mas_caracter(char* cadena, char caracter)
{
int i=0;
int largo_texto = strlen(cadena)+1;
char cadena_nueva[largo_texto+1];
for( i=0; i < largo_texto; i++)
{
cadena_nueva[i] = cadena[i];
if(cadena[i] == '\0')
{
cadena_nueva[i]= caracter;
}
}
return cadena_nueva;
}
You SHOULD NOT (although yes, sometimes it CAN return the expected result!) return local variable pointer from a function as it is allocated on stack!
Here's an excellent explanation as to why: Can a local variable's memory be accessed outside its scope?
To make your code work,replace
char cadena_nueva[largo_texto+1];
with
char* cadena_nueva = (char*)malloc(sizeof(char)*(largo_texto+1));
Don't forget to free() it when you are done using it
It would really help you if you'd read about heap & stack memory storage:
What and where are the stack and heap?
http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html
http://www-ee.eng.hawaii.edu/~tep/EE160/Book/chap14/subsection2.1.1.8.html

Resources