C :: Free A String Literal From Memory?

Jan 8, 2014

This compiles o.k.:

Code:

int main(void){
char *a;
a = (char*) malloc (100*sizeof(char));

[Code]....

I get an error saying "pointer being freed was not allocated". This happens for free(a), free(*a), free(&a), free(&*a).

So if I no longer need "1234567"... how do I get rid of this memory element?

View 7 Replies


ADVERTISEMENT

C :: Free Allocated Memory For Structure?

Mar 16, 2014

I'm trying to free allocated memory for structure. It seems like free() gets only pointer and not regular types . my question is basic and simple – is passing pointer to free() frees the pointer or the variable it points at? or both?

View 2 Replies View Related

C :: Malloc Is Used To Allocate Free Memory To A Pointer

Nov 5, 2014

There is a part in the lesson that explains how malloc is used to allocate free memory to a pointer and gives us 2 examples:

Code:

float *ptr = malloc( sizeof(*ptr) ); and Code: float *ptr;
ptr = malloc( sizeof(*ptr) );

From my logic in the first case we allocate the memory to *ptr and in the second to ptr.

It's a bit confusing, am I missing something?

View 14 Replies View Related

C :: Free Not Working After Malloc Was Used To Allocate Memory

Jun 13, 2014

Consider this program:

Code:

// sb_string class v1.04

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct sb_string {

[Code] ....

And here is the output I got:

Code:
[harshvardhan@hari-rudra] ~/Desktop% gcc49 -o test test.c
[harshvardhan@hari-rudra] ~/Desktop% ./test
-before Value of len = 1
(in_function)-before Value of len = 1
(in_function)-after Value of len = 1

-after Value of len = 1 I was trying to make a little easier to work with string. Once the memory is allocated by malloc via sb_init() function, the sb_massacre function wasn't working to deallocate the memory. I had used multiple versions of gcc and clang but the result is same.

View 4 Replies View Related

C++ :: Free Up Memory In Client Server Program

Nov 22, 2013

How to free the memory and address,value

Server:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

[Code] .....

Client:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>

[Code] .....

View 1 Replies View Related

C++ :: Using Malloc / Free Multiple Times Leaves Less Memory?

Apr 17, 2014

My application calls malloc in multiple subroutines, finally releasing all using free. This is done using my zalloc library (see my other post: [URL] .....

Somehow, when the applications tries to detect the available ammount of memory at the end of the test (allocating, freeing, testing), the freemem function gives me about 4-6MB less memory than at the start of the test? (out of 21MB available on the device at the start).

All memory is allocated and freed using the malloc/free routines within the library, with the exception of the SDL functions, which are registered externally on allocation and release.

View 3 Replies View Related

C++ :: Vector Of Int Class - How To Delete Pointer X In Destructor To Free Memory

Feb 25, 2015

An attempt to create a class which is basically a mimic of vector<int> i don't seem to know how to delete pointer x in a destructor to free memory, also on pushback and pushfront methods, i can't free y when i implement delete[] y; y=NULL; i get some NULL out put when cout 'ing the object in main, why is that happening and how do i free memory y.

#include<iostream>
using namespace std;
class vectorOfint{
int* x;
int size;
public:
vectorOfint();

[Code] .....

View 6 Replies View Related

C :: Free Memory From A Dynamically Allocated Array Of Pointers To Linked Lists

Feb 26, 2013

Having some frustrating issues trying to free memory from a dynamically allocated array of pointers to linked lists. I think the problem is in how I initialize the pointers to NULL. Is there a more elegant way to have the program recognize that the list is empty so it knows to create a head node for the linked list in the function 'add_end_stub_to_array'?

I ran the code through Valgrind and it says that memory is definitely lost from this array.

This is the structure definition.

Code: struct stub_edge {
int loc_id;
int anim_type;
int mkt;
struct stub_edge *next_node;
};

Here is the code snippet from main allocating and deallocating memory to the array.

Code:

struct stub_edge **stub_list = (struct stub_edge **)malloc( sizeof(struct stub_edge *) * 12);
for (i = 0; i < 12; i++)
{
stub_list[i] = (struct stub_edge *)malloc(sizeof(struct stub_edge));
stub_list[i] = NULL;
}
stub_list = add_end_stub_to_array(end_stubs, stub_list);
destroy_end_stub_array(stub_list);

Here the function for adding nodes to the lists by reading through a dynamically allocated 2D array. (The end_stubs array is ordered by month and each linked list represents events occuring within the month).

Code:

struct stub_edge **add_end_stub_to_array(int **end_stubs, struct stub_edge **list)
{
long int i = 0;
int mon = 0;
struct stub_edge *current_node1;
struct stub_edge *new_node1;
int break1 = 0;
while(i < num_edges && break1 == 0 && mon < 12)

[Code]...

Here is the function for freeing memory from the list.

Code:

void destroy_end_stub_array(struct stub_edge **list)
{
if(list != NULL)
{
int mon = 0;
struct stub_edge *current_node1;
struct stub_edge *new_node1;
for(mon = 0; mon < 12; mon++)

[Code]...

View 1 Replies View Related

C/C++ :: Taking String As Input And Making It As Whole Array (string Literal)

Oct 19, 2014

Very new to programming, and I know that there must be another way on inputting a string into each array cells not by just inputting it one by one, but as a whole. My code at the meantime is: [URL]

View 1 Replies View Related

C++ :: String Literal With Constexpr

May 28, 2013

I have a binary identifier which I tried to make a constexpr since all of its calculations would never occur during runtime (this is true for literal identifiers, right?). Since constant expressions can only have one instruction, I tried to cheat a little and returned an immediate call to a lambda function. This failed miserably however. I tried making a constexpr function pointer and called that from _binary down below, but the compiler still felt that it wasn't a constexpr. Why is this? And is there a way to make a function like _b below constexpr?

#include <iostream>
#include <cstddef>
using std::cout;
using std::endl;
long unsigned //Original
operator"" _b(const char* const literal, size_t lsize){

[Code] .....

View 4 Replies View Related

C :: Assigning A Pointer To A String Literal

Sep 13, 2013

In another forum, this example code fragment was stated as being an example of undefined behavior. My understanding is that a literal string exists from program start to program termination, so I don't see the issue, even though the literal string is probably in a different part of memory.

Code: /* ... */
const char *pstr = "example";
/* or even */
char *pstr = "example";
/* as long as no attempt is made to modify the data pointed to by pstr, */
/* unless pstr is later changed to point to a stack or heap based string */

View 11 Replies View Related

C++ :: Use Of A Backspace Character In A String Literal

Apr 19, 2014

In the following char array, notice the use of a backspace character in a string literal: ''.

char text1[50] = "aHello,
World! Mistakee was "Extra 'e'"!
";

What exactly does a backspace character do here? When the compiler evaluates this line, does it actually delete the previous character, like when you press the backspace button on the keyboard?

View 1 Replies View Related

C/C++ :: Pointer-to-char To String Literal?

Oct 6, 2014

how string literal that works with the cin object?

char * str = "This is a string constant";

Is the str stored the address of the first character of the string literal?

But some books just state that the pointer-to-char (char pointer) stores the address of the string literal". So just wonder how it is.

When it is used with cout, cout just treats it like a string and instead of printing the address, it just prints out all characters one by one until it reaches the terminated null character.

If this is the case, then I am just wondering how cin works with it? with a statement like this cin >> str; ?

Does the computer allocate enough memory for it? and then cin stores the first character into the first address and then advances to the next address and stores the next character?

View 1 Replies View Related

C++ :: Initializing Const Struct When Data Is A String Literal

Feb 23, 2015

I have a struct like this:

Code:
struct String{
char* data;
std::size_t size;
};

I would like to be able to create const variables of this type for string literals.

Code:
const String message;

Is there an elegant way to create a const String like this when data is a string literal?

I tried this:

Code:
const char *string_data = "Hello";
size_t string_size = strlen(string_data) + 1;
const String string = {string_data, string_size};

The problem with that is that string.data isn't considered const during the initialization of the String struct so the compiler throws an error. It doesn't feel very elegant to do it like this either way.

Is there an elegant solution to this problem? I would like to avoid making a copy of the string literal.

View 7 Replies View Related

C++ :: Function Works When Passed String Literal But Not A Variable

Jul 10, 2014

I'm making a .json loader for a project that I'm working on, and to simplify things, I decided to make all the root attributes named in a separate file. Here's my problem: my loading function, Add(const char* id), works just fine when I pass it a string literal.

However, when I use a function that iterates through a vector list, even with the exact same definitions as the literal, it returns the error: std::out_of_range at memory location 0x0026fb30

I've stepped through it with the VS2010 debugger about a hundred times, checked against memory locations, and just have done everything I can think of, all to no avail..

The code, with data-checking omitted:

The std::map I'm adding to:

static std::map<const char*, Item*> *s_mItems;
Initialized as std::map<const char*, Item*> *Item::s_mItems;

Add() Function (Works by itself with a literal):

static bool Add(const char* id) {
...
std::string name = node.Get("name").ToString();
std::string desc = node.Get("description").ToString();
int rarity = StrToRarity(node.Get("rarity").ToString());

[Code] ....

AddList() function, where the program always breaks:

static void AddList(std::vector<std::string> list) {
for(std::vector<std::string>::iterator it = list.begin(); it != list.end(); it++) {
Add(it->c_str());
}
}

View 3 Replies View Related

C/C++ :: SDL LoadBMP Fails To Load A Passed String Literal

Jan 24, 2014

Background: I'm using SDL and CodeBlocks and trying to make a Graphics class that would simplify some SDL operations such as drawing and loading images.

Issue: The loadImage function in the graphics class fails to load the image correctly and so the program prints out a blank window during run-time. I've tried multiple ways of passing a string literal into the function the surface temp fails to load and so background in Game fails to load. After testing it several times, I'm pretty sure that the issue lies with SDL_LoadBMP not registering the passed variable for whatever reason. I know the image is in the right place as writing SDL_LoadBMP("./Graphics/image.bmp"); brings it up just fine.

Current Code:

Main simply creates a Game object and execute(), so I didn't feel the need to put it on here.

Game.h
#ifndef GAME_H
#define GAME_H
#include "SDL/SDL.h"
#include "SDL/SDL_ttf.h"
#include "Graphics.h"
#include <string>
#include <cstring>
using namespace std;

//GLOBAL CONSTANTS
//game window settings

[Code] ....

Output: A blank window. (It should show the background image but doesn't.)

Note: I originally wrote it as gfx.loadImage(background, "./Graphics/image.bmp") but that gives me a conversion warning and still fails to show the image when the program runs. I've tried looking up examples similar to what I was doing but no one else seems to have this problem.

View 3 Replies View Related

C :: Cycling Through Memory To Print String With And Without Function

Feb 10, 2014

Anyways, I have a problem where I'm trying to cycle through memory via pointers to print a string. Here is my code:

Code:

#include <stdio.h>
int main(void){
char word[]="hello there";

[Code]....

This seems to effectively portray what I want

How do I print a string using the same method for(;*pointer!='/0';pointer++) without a function?

View 2 Replies View Related

C# :: Instantiation Of Literal Strings?

Apr 5, 2012

I have a huge xml file from which the key and value attributes are selected among other things.

Code:
foreach (
XmlNode node in
configProductCode.SelectNodes("/configuration/appSettings/add"))
{
ConfigProductCode cpc = new ConfigProductCode();

XmlAttribute keyAttr = node.Attributes["key"];
XmlAttribute valAttr = node.Attributes["value"];
// etc
}

How does C# handle the instantiation of literal strings? does it make a new object with allocating heap memory on every iteration or just once?

View 2 Replies View Related

C++ :: Create User Define Literal?

Jul 14, 2014

In C++ there are a number of primitives that are not defined in terms of other types. By this I'm thinking

int a = 1;
char b = 'M';
float c = 3.45f;
short d = 0xC3A3;

Is it possible to define your own literal? What I would like to do is have a hex literal for a data type where n = sizeof(data_type). If this type were a big integer, then I would want something like:

BigInt e = 0x13CA9B0C98D983E912DA0B0A9F87E0;

My goal is to assign a value from one contingous chunk of bytes and to not do it with a string.

View 1 Replies View Related

C++ :: Overloading Operator + For Literal Strings?

Sep 8, 2013

i have 1 nice write() function:

void write() {
cout <<"";
}
template <typename A, typename ...B>
void write(A argHead, B... argTail) {
cout << argHead;
write(argTail...);
}

these function works. but if i concat literal strings with '+', i must use '(string)'. so i'm trying overload the operator + for concat literal strings, but without sucess:(

string operator + ( char *value1) {
string value2;
value2=(string) value2+value1;
return value2;
}

(these functions are inside of my Console class)

View 2 Replies View Related

C/C++ :: Difference Between Literal And Symbolic Constants?

Jun 29, 2014

"A constant, like a variable, is a memory location where a value can be stored. Unlike variables, constants never change in value. You must initialize a constant when it is created. C++ has two types of constants: literal and symbolic.

A literal constant is a value typed directly into your program wherever it is needed. For example, consider the following statement:

long width = 5

This statement assigns the integer variable width the value 5. The 5 in the statement is a literal constant. You can't assign a value to 5, and its value can't be changed.

The values true and false, which are stored in bool variables, also are literal constants.

A symbolic constant is a constant represented by a name, just like a variable. The const keyword precedes the type, name, and initialization. Here's a statement that sets the point reward for killing a zombie:

const int KILL_BONUS = 5000;

Whenever a zombie is dispatched, the player's score is increased by the reward:

playerScore = playerScore + KILL_BONUS;

If you decide later to increase the reward to 10,000 points, you can change the constant KILL_BONUS and it will be reflected throughout the program. If you were to use the literal constant 5000 instead, it would be more difficult to find all the places it is used and change the value. This reduces the potential for error."

what's the difference? Here is a program to demonstrate what I'm having trouble conceptualizing.

#include <iostream>
using namespace std;
int main() {
int width = 10, length = 10;
int area = width * length;
cout << "Width: " << width << endl;
cout << "Length: " << length << endl;
cout << "Area: " << area << endl;
return 0;
}

Now, why would it be harder to go in and changed a regularly defined integer than one defined with the 'const' keyword proceeding it? For example, the width and length variables. My confusion comes from the point that they seem to both simply be variables with a value assigned to them. I feel as if the process of having to change a literal constant's value is synonymous to the process of having to change a symbolic constant's.

View 3 Replies View Related

C++ :: Append Comma To A String - Dynamic Memory Allocation Error

May 16, 2012

Trying to append a comma to a string. Getting "Segmentation Error" on Solaris when the function is entered the second time.

Code:

// Appends a comma to the given string
void appendComma(char* instring) {
if (instring == NULL) {
instring = realloc(NULL, strlen(","));
strcpy(instring,",");

[Code] .....

View 14 Replies View Related

C :: Display Numbers That Are Passed As Literal ASCII Characters To LCD

Mar 20, 2014

What shall I learn in order to send values from 0.00 to 5.00? I'm working with they Hitachi 16x2 LCD display.I've been sending/displaying literal values on it all day.

Code:

SendCharater(unsigned char val)

where the variable val corresponds to the LCD character table.I can also send Hello World to the display, like so:

Code:

void putsXLCD(unsigned char *buffer){
while(*buffer) // Write data to LCD up to null
{
while( BusyXLCD() ); // Wait while LCD is busy
SendCharacter(*buffer); // Write character to LCD
buffer++; // Increment buffer
}
return;
}

I could type in putsXLCD("5.00") in order to display it on the LCD, but how do I implement this automatically for values, e.g. 0.00 to 5.00?It appears I can only pass literal values through the function SendCharacter, meaning that in order to display "0" I have to pass the value 0x30 (the hex value of "0" on the LCD Table).

My current thought process:Much like passing "Hello World" in the function putsXLCD(), I need to assign a pointer that points at each value in the "array" that I need to send. E.g., I need to send 3.24, so I need to point to "3", fetch the corresponding hex value in the LCD table, in this case 0x34, and the pass this 0x34 into the SendCharacter function, and so on. So, if this is the case, how can I fetch the corresponding hex value?

View 7 Replies View Related

Visual C++ :: How To Directly Pass Wstring (literal) To Function

Feb 5, 2013

I am wondering if I have the following parameter to pass in to a function

Code : void Load(std::wstring filename);

This statement is wrong.

Code : Load("DataMesh.x");

I don't want to pre-declare a variable. How do I directly pass a wstring (literal) to this function.

View 2 Replies View Related

C :: Segmentation Fault At Free Call

Jul 7, 2014

Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
/* h(a)=abcab,h(b)=acabcb,h(c)=acbcacb */
void h_i(int i, char *w, char *a, char *b, char *c)

[Code] .....

Above program increases string like this example.

Let say h(0)=01 and h(1)=10 and let say our first string is w=0 h(w)=01, h^2(w)=0110 h^3(w)=01101001..etc.

We have used h map, which is given in the program comment statement. Same thing, program is doing for three letters. These three letters we have passed as argument in h_i function. e.g. h_i(2,w,"a","d","g") function will apply the 3 letter map h(definition is given in commented form in program) 2 times on string w.

In program w=a; and three letters are a, d and g. /* h(a)=abcab,h(b)=acabcb,h(c)=acbcacb */ here b=d and c=g.

Above program gives core dump at free(w2) free(w1). if we remove these free statements then it gives correct answer. But, we want to free w1 and w2 in the above code. How can we make free both w1 and w2 strings?

View 4 Replies View Related

C :: Way To Free Unsigned Pointer Array In Best Way

Feb 24, 2013

how is the best way to free unsigned pointer array allocated with cmallc?

Code:

uint8_t *buf;
buf = cs_calloc(ca->len + 13);

i do like this , but i know this is not quite right , since i got compile warning passing argument 1 of ‘free’ makes pointer from integer without a cast

Code:

for (i = 0; i < ca->len + 13; i++)
{
free(buf[i]);
buf[i] = NULL;
}

free(buf); do i need to free each element of array like above?

View 6 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved