473,508 Members | 2,140 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Char pointers in C

22 New Member
Hi.

I'm trying to figure out pointers and memory allocation in C. I've read quite a few explanations on the internet and have read in a few books that I've got, but I'm not so much smarter yet...

What I want do do is to create an array of five pointers to characters... I want to make it possible to assign a pointer to the params array tohrough the setParams function. I don't understand what I have not gotten, but there is certainly something. It seems like this works:

Expand|Select|Wrap|Line Numbers
  1. char * val1 = malloc(30);
  2. free(val1);
but this doesn't:

Expand|Select|Wrap|Line Numbers
  1. char * val1 = malloc(30);
  2. val1 = "Hei og hå!";
  3. free(val1);
This seems logical to me, because the val1 variable is first instantiated with memory allocated and then set to "Hei og hå". I would assume the memory location returned from the malloc call would be lost, right?. The only walkaround for this problem as far as I have understood is to assign one char at the time and increase the pointer one position at the time and do

Expand|Select|Wrap|Line Numbers
  1. *val1 = 'H';
and then increase the pointer with val1++ for each letter. It sounds too complicated to be right.. Or is it like this? Another problem with that solution is that when I've moved the pointer a few positions I have lost the start position of the var and is no longer able to free the var because I don't have the right position.

If someone could straighten this out it would be awesome. I guess it's not so hard, but it is hard to get a grip on when you don't fully understand how the pointers work in C.

The code I'm trying to get to work is to large to post here I think, but if I get the idea on how to get the following piece of code right, much is done I think.

NOTICE! If your going to compile it, compile with "-DDEBUG -DSOLO" to get the main method and the includes in the compile.
Expand|Select|Wrap|Line Numbers
  1. #ifdef DEBUG
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #endif
  5.  
  6. #include "bitwise.h"
  7.  
  8. int power(int num, int power) {
  9.     int i, res=1;
  10.     for(i=0; i<power; i++) {
  11.         res = res*num;
  12.     }
  13.     if(power==0)
  14.         return 1;
  15.     else
  16.         return res;
  17. }
  18.  
  19. void setBit(unsigned char * map, int num, int val) {
  20.     if(val != getBit(map, num))
  21.         map[num/8] = (map[num/8]^power(2,7-(num%8)));
  22. }
  23.  
  24. int getBit(unsigned char * map, int num) {
  25.     return ((map[num/8]>>(7-num)) & 1);
  26. }
  27.  
  28. #ifdef SOLO
  29. char * setParam(char * params[], unsigned char * map, int n, char * val) {
  30.     params[n] = val;
  31.     setBit(map, n, 1);
  32.     return params[n];
  33. }
  34.  
  35. char * getParam(char * params[], unsigned char * map, int n) {
  36.     //if(getBit(map, n))
  37.         return params[n];
  38.     //else
  39.     //    return NULL;
  40. }
  41.  
  42. void removeParam(char * params[], unsigned char * map, int n) {
  43.     if(getBit(map, n)) {
  44.         printf("sletter: %x\n",params[n]);
  45.         free(params[n]);
  46.         setBit(map,n,0);
  47.     }
  48. }
  49.  
  50. int paramUsed(char * params[], unsigned char * map, int n) {
  51.     return getBit(map, n);
  52. }
  53.  
  54. int main() {
  55.     unsigned char status = 0;
  56.     char * params[5];
  57.  
  58.     char * val1 = malloc(30);
  59.     val1 = "Hei og hå!";
  60.  
  61.     printf("%s == %s\n",val1,setParam(&params[0], &status, 0, val1));
  62.     printf("%s\n",getParam(params, &status, 0));
  63.     printf("Used: %d\n",paramUsed(params, &status, 0));
  64.     removeParam(params, &status, 0);
  65.     printf("%s\n",getParam(params, &status, 0));
  66.     printf("Used: %d\n",paramUsed(params, &status, 0));
  67.     return 0;
  68. }
  69. #endif
Thanks in advance :)

K
Oct 11 '08 #1
11 4921
boxfish
469 Recognized Expert Contributor
Expand|Select|Wrap|Line Numbers
  1. char * val1 = malloc(30);
  2. val1 = "Hei og hå!";
  3. free(val1);
  4.  
Well hmm. I've only programmed in C++, so I'm not that familliar with malloc, but it seems you have to cast it to the data type you want; in this case, char*. As for copying a string into the allocated memory, you don't have to do it yourself; use the strcpy function. So the above code should be
Expand|Select|Wrap|Line Numbers
  1. char * val1 = (char *)malloc(30);
  2. strcpy(val1, "Hei og hå!");
  3. free(val1);
  4.  
Hope this helps.
Oct 12 '08 #2
Tassos Souris
152 New Member
Expand|Select|Wrap|Line Numbers
  1. char *val = malloc(30);
  2.  
  3. /* Advice: change that to: */
  4.  
  5. char *val = ( char * )calloc( 30, sizeof( char ) );
  6.  
This allocates a space for 30 characters. It returns the initial address and stores it in the val pointer variable. So, val now points to that space.

Expand|Select|Wrap|Line Numbers
  1. val = "....";
  2.  
Do not forget that strings in C are represented as sequences of characters in memory.
In this statement, val gets the initial address of the string, so now it points there...

When you do:
Expand|Select|Wrap|Line Numbers
  1. free( val );
  2.  
you have two problems:
-> First, you have lost where the space you allocated with malloc (or calloc) resides in memory and you cannot free it anymore.
-> Second, your program is most likely to get messy there.. free accepts a pointer earlier returned by a call to malloc, calloc or realloc.. In this case, the address of the string "..." is passed which might be in read-only memory (if your are lucky cause then you will get a assertion).

The correst way to do this is to copy the string to the newly allocated space...

hope i helped
Oct 12 '08 #3
oler1s
671 Recognized Expert Contributor
I'm not that familliar with malloc, but it seems you have to cast it to the data type you want
No. You don't have to cast malloc, and you probably don't want to, as it doesn't help but can hurt. Unless you want to compile under C++, C will implicitly do the cast.

krreks, you wouldn't write val1++. You can index it, such as val1[2]. You essentially have an array (dynamically allocated), and you can index that array, right? Think about arrays.

Also read http://c-faq.com/ on the relevant sections. The pointers vs. arrays section is particularly helpful.
Oct 12 '08 #4
krreks
22 New Member
Thanks a lot for great pointers to answers! I had been scratching my head for quite a few hours and it was great getting some answers that was not in-a-conversation-answers in a mailing list :) A few new questions arises and it would be wonderfull to get some answers to those as well..

1. So the strcpy seems to be the way to go then. I wonder though why this works like it does:

Expand|Select|Wrap|Line Numbers
  1. char * val1 = (char *) malloc(5);
  2. printf("%s\n",val1);
  3. strcpy(val1, "test");
  4. free(val1);
  5. printf("%s\n",val1);
It seems to hold the value of the pointer even after it has been freed? Is that right or is there still an error?

2. Is the following piece of code right? I have an array of pointers and want to point one of the elements in the array to a given memory location allocated for another pointer.

Expand|Select|Wrap|Line Numbers
  1. char * setParam(char * params[], unsigned char * map, int n, char * val) {
  2.     params[n] = val;
  3.     setBit(map, n, 1);
  4.     return params[n];
  5. }
  6.  
  7. void removeParam(char * params[], unsigned char * map, int n) {
  8.     if(getBit(map, n)) {
  9.         printf("sletter: %s\n",params[n]);
  10.         free(params[n]);
  11.         setBit(map,n,0);
  12.     }
  13. }
  14.  
  15. int main() {
  16.     unsigned char status = 0;
  17.     char * params[5];
  18.  
  19.     char * val1 = malloc(30);
  20.     strcpy(val1, "Hei og hå!");
  21.     setParam(&params[0], &status, 0, val1)
  22.     removeParam(params, &status, 0);
  23. }
NOTICE! The get- and setBitmap functions is a bitmap to keep track of used and unused pointers and is known to work.

It compiles and executes right, but here as well as the previos code, the value of the pointer is accesable after the memory is freed...
Oct 12 '08 #5
drhowarddrfine
7,435 Recognized Expert Expert
Freeing memory does not "reset" a pointer. It will still point at the address reserved by malloc. It's just that the memory itself is unused or, possibly, now used for something else.
Oct 12 '08 #6
Banfa
9,065 Recognized Expert Moderator Expert
It seems to me that you need to look up the standard library function strcpy.
Oct 12 '08 #7
boxfish
469 Recognized Expert Contributor
You don't have to cast malloc, and you probably don't want to, as it doesn't help but can hurt.
I thought you had to cast it because this code
Expand|Select|Wrap|Line Numbers
  1. char * val1 = malloc(30);
  2. strcpy(val1, "Hei og hå!");
  3. cout << val1;
  4. free(val1);
didn't compile on my Dev-C++ compiler. It says
invalid conversion from `void*' to `char*'
The error went away when I did a typecast. Is there anything I'm doing wrong? I also found a couple of examples, like this one, which use a type cast.
Oct 12 '08 #8
JosAH
11,448 Recognized Expert MVP
I thought you had to cast it because this code
didn't compile on my Dev-C++ compiler. It says
invalid conversion from `void*' to `char*'
The error went away when I did a typecast. Is there anything I'm doing wrong? I also found a couple of examples, like this one, which use a type cast.
The OP is using C, you were using C++. In C you can freely implicitly cast to and
from a void* to any other type of pointer. In C++ the cast needs to be explicit.

kind regards,

Jos
Oct 12 '08 #9
boxfish
469 Recognized Expert Contributor
Okay, thanks, I get it. I had expected that all C code would compile for me, because of the backwards-compatibility thing.
Oct 12 '08 #10
krreks
22 New Member
Freeing memory does not "reset" a pointer. It will still point at the address reserved by malloc. It's just that the memory itself is unused or, possibly, now used for something else.
That sounds right. I've really tried and failed a lot the last few days, but it's starting to pay off :)

Thanks a lot for all the answers, explanations and your time.

Yours sincerely
Oct 12 '08 #11
Laharl
849 Recognized Expert Contributor
Okay, thanks, I get it. I had expected that all C code would compile for me, because of the backwards-compatibility thing.
Not all C is valid C++, just most of it.
Oct 12 '08 #12

Sign in to post your reply or Sign up for a free account.

Similar topics

21
18823
by: Bret | last post by:
I'm curious why char** argv is acceptable in the main() declaration. In the comp.lang.c FAQ (question 6.18) it says that pointers to pointers and pointers to an array are not interchangable. ...
5
2512
by: Sona | last post by:
I understand the problem I'm having but am not sure how to fix it. My code passes two char* to a function which reads in some strings from a file and copies the contents into the two char*s. Now...
3
2194
by: sieg1974 | last post by:
Hi, I have made this simple program to understand char ** pointers, but I still having many questions. int main() { char ** testPointerPointerChar = 0; char * A = "string01";
19
14491
by: gaga | last post by:
I can't seem to get this to work: #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *names; char **np;
5
3939
by: jab3 | last post by:
(again :)) Hello everyone. I'll ask this even at risk of being accused of not researching adequately. My question (before longer reasoning) is: How does declaring (or defining, whatever) a...
5
5331
by: max | last post by:
Dear all, I did the following analysis to conclude that the following pointer types are not compatible. Please let me know If my analysis and interpretation of the C standard are correct: ...
4
2139
by: Xavier Roche | last post by:
Hi folks, I have a probably rather silly question: is casting a char array in a char* a potential source of aliasing bug ? Example: a fonction returning a buffer taken in a circular buffer ...
13
3116
by: arnuld | last post by:
i see the use of pointers, from K&R2 but what is the use of: 1. "pointer to pointer": char c; char** ppc; 2. pointer to function:
21
2719
by: arnuld | last post by:
int main() { const char* arr = {"bjarne", "stroustrup", "c++"}; char* parr = &arr; } this gives an error: $ g++ test.cpp test.cpp: In function 'int main()': test.cpp:4: error: cannot...
4
3189
by: Paul Brettschneider | last post by:
Hello all, consider the following code: typedef char T; class test { T *data; public: void f(T, T, T); void f2(T, T, T);
0
7227
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7331
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7391
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
5633
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4713
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3204
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3188
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
768
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
424
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.