Returning a string literal?

This question already has an answer here:

  • Can a local variable's memory be accessed outside its scope? 16 answers

I have a dynamically allocated array of pointers, each of which points to a line of text in a file. I need to extract the fourth column of the file (the values in the file are separated by commas), so that I can be able to sort the file by that column later on. I've been able to extract the fourth column text, however I am unable to return it to use in my main function, and when I return it, it's blank, what could be the problem?

getStart finds the comma right before the needed column

int getStart(char** addresses, int index) { int i = 0; int count = 0; for(i=0;i < strlen(addresses[index]); i++) { if(addresses[index][i] == ',') count += 1; if(count == 3) return i+1; } }

getStop finds the comma right before the end of the needed column

int getStop(char** addresses, int index) { int i = 0; int count = 0; for(i=0;i < strlen(addresses[index]); i++) { if(addresses[index][i] == ',') count += 1; if(count == 4) return i; } }

getSubject takes all the characters in between the start and stop, and puts them into an array (which is what I need to return to main)

char* getSubject(char** addresses, int index) { int i = 0; int start; int stop; char* final; char subject[10]; start = getStart(addresses, index); stop = getStop(addresses, index); for(start; start<stop; start++) { subject[i] = addresses[index][start]; i++; } final = subject; printf("%s %s\n", final, subject); return final; }

The way that I know the function work is that

printf("%s %s\n", final, subject);

prints the proper values, however when I call it in main as follows:

char* test; test = getSubject(addresses, 43); printf("%s\n", test);

test prints a blank value. Why is this?


You make final point to the local array subject, and then return that pointer. That means you are in fact returning a pointer to the local subject array, an array that goes out of scope once the function returns, leaving you with a stray pointer and undefined behavior.

You need to allocate memory for the final string, and there are generally two ways of doing it:

  1. Use e.g. strdup in the function to allocate memory and return a pointer to that new memory.
  2. Pass in a pointer to a buffer of enough memory as an argument to the function, and copy the string to that buffer.

you are returning a pointer to a stack variable, you cant do that. The stack is cleared once you return. Make a copy

return strdup(final);

the call must free it when finished with it

Category:c# Time:2017-12-02 Views:2

Related post

  • Is returning a string literal address from a function safe and portable? 2010-03-03

    I need a function to return a string that will only be accessed read-only. The string contents is known at compile time so that I will use a string literal anyway. I can return something like std::string: std::string myFunction() { return "string"; }

  • R function that returns a string literal 2009-12-09

    I have a vector: c(1,2,3) Calling print() on this value gives [1] 1 2 3 Is there a function that takes a vector and gives the string c(1,2,3)? --------------Solutions------------- You can use deparse: R> x <- c(1, 2, 3) R> deparse(x) [1] "c(

  • Why is returning a reference to a string literal a reference to a temporary? 2015-07-16

    A regular string string literal has the following definition: Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the stri

  • Lifetime of a const string literal returned by a function 2010-04-05

    Consider this code: const char* someFun() { // ... some stuff return "Some text!!" } int main() { { // Block: A const char* retStr = someFun(); // use retStr } } My question is in the function sumFun() where is "some Text!!", stored (i think may be i

  • Is it safe to return a pointer to a string literal to the caller? 2012-04-02

    char* stringReturn() { char a[] = "Array of characters"; //return a; // I know stack allocation should not be returned char *b = "Pointer to a string"; return b; // Is it safe ? } int main() { char *str = stringReturn (); cout<< str; return 0;

  • Can I convert a C# string value to an escaped string literal 2008-11-27

    In C#, can I convert a string value to a string literal, the way I would see it in code? I would like to replace tabs, newlines, etc. with their escape sequences. If this code: Console.WriteLine(someString); produces: Hello World! I want this code: C

  • How to create a UTF-8 string literal in Visual C++ 2008 2009-03-27

    In VC++ 2003, I could just save the source file as UTF-8 and all strings were used as is. In other words, the following code would print the strings as is to the console. If the source file was saved as UTF-8 then the output would be UTF-8. printf("C

  • in c# when returning a string from a function does the memory get freed? 2009-03-30

    This is what I mean: class mycalss { string myfunc() { string str="hello"; return str; } } ... static void main() { string str2; str2=myfunc(); ... ... } In this case is there a risk that the garbage collector might delete the contents of str2 becaus

  • concatenating/printing a string literal 2009-04-14

    I'm running into an odd problem with concatenating or printing strings. I have a char * that can be set to one of a few values of string literal. char *myStrLiteral = NULL; ... if(blah) myStrLiteral = "foo"; else if(blahblah) myStrLiteral = "bar"; An

  • Should I return std::strings? 2009-06-23

    I'm trying to use std::string instead of char* whenever possible, but I worry I may be degrading performance too much. Is this a good way of returning strings (no error checking for brevity)? std::string linux_settings_provider::get_home_folder() { r

  • Multiline String Literal in C# 2009-07-08

    Is there an easy way to create a multiline string literal in C#? Here's what I have now: string query = "SELECT foo, bar" + " FROM table" + " WHERE id = 42"; I know PHP has <<<BLOCK BLOCK; Does C# have something similar? --------------Soluti

  • Javascript - Replacing the escape character in a string literal 2009-09-03

    I am trying to replace the backslash (escape) character in a Javascript string literal. I need to replace it with a double backslash so that I can then do a redirect: var newpath = 'file:///C:\funstuff\buildtools\viewer.html'.replace(/\\/g,"\\"); win

  • Sizeof string literal 2009-09-08

    The following code #include <iostream> using namespace std; int main() { const char* const foo = "f"; const char bar[] = "b"; cout << "sizeof(string literal) = " << sizeof( "f" ) << endl; cout << "sizeof(const char* cons

  • How to treat a returned/stored string like a raw string in Python? 2009-11-24

    I am trying to .split() a hex string i.e. '\xff\x00' to get a list i.e. ['ff', '00'] This works if I split on a raw string literal i.e. r'\xff\x00' using .split('\\x') but not if I split on a hex string stored in a variable or returned from a functio

  • C++: Constructor accepting only a string literal 2010-01-11

    Is it possible to create a constructor (or function signature, for that matter) that only accepts a string literal, but not an e.g. char const *? Is it possible to have two overloads that can distinguish between string literals and char const *? C++

  • How to detect the passing of a string literal to a function in C? 2010-02-23

    I am trying to implement an eqivilent version of perl's chomp() function in C and I have come across a corner case where a string literal passed as the argument will cause a segmentation fault (rightfully so). Example chomp("some literal string\n");

  • C++ string literal data type storage 2010-02-24

    void f() { char *c = "Hello World!" } Where is the string stored? What's the property of it? I just know it is a constant, what else? Can I return it from inside of the function body? --------------Solutions------------- it is packaged with your bina

  • model.__unicode__() returning russian string cause TemplateSyntaxError 2010-02-25

    code: class Gallery(models.Model): title = models.CharField(max_length=100) description = models.TextField(blank=True) created = models.DateField(auto_now_add=True) class Meta: verbose_name = 'галерея' verbose_name_plural = 'галереи' def __unicode__(

  • How would you convert a String to a Java string literal? 2010-03-16

    This is sort of the Java analogue of this question about C#. Suppose I have a String object which I want to represent in code and I want to produce a string literal that maps to the same thing. Example hello, "world" goodbye becomes hello, \"world\"\

Copyright (C), All Rights Reserved.

processed in 0.565 (s). 13 q(s)